How do I fix this? I want to add a blank line at the end.
string SqlText = "SELECT * FROM [Train]";
SqlDataAdapter da = new SqlDataAdapter (SqlText, ConnStr);
DataSet ds = new DataSet ();
da.Fill (ds, "[Train]");
dataGridView1.DataSource = ds.Tables ["[Train]"]. DefaultView;
Answer 1
Once you put something in the DataSource
property, the data binding mechanism (Binding) is enabled. When binding is enabled, manual control of the display is not allowed, which is what the error text informs you about.
When working with data binding, you need to change the data source.
One of the solutions:
-
Instead of the local variable
DataSet ds
, use a private form field such asprivate DataTable Trains
(you only have one table) so that it can be accessed from any method forms. -
Fill in the field and grid:
string SqlText = "SELECT * FROM [Train]"; SqlDataAdapter da = new SqlDataAdapter (SqlText, ConnStr); da.Fill (Trains); dataGridView1.DataSource = Trains;
-
Add blank line to
DataTable
rebind dataTrains.Rows.Add (Trains.NewRow ()); // re-bind if necessary, but this is usually unnecessary dataGridView1.DataSource = null; dataGridView1.DataSource = Trains;
After that, you will have a new line at the bottom.
One of the alternative solutions:
- make a model class (conventionally
Train
) with the required public properties. - Fill model objects with the data obtained from the request.
- Collect the obtained objects into the
BindingList
collection, which we put in theDataGridView.DataSource
. - Add new blank objects to this collection.
- In addition, it will be useful to implement the
INotifyPropertyChanged
interface in the model class, it somewhat facilitates the work of the binding mechanism and will automatically display changes to the data made in the code.
In general, the topic of data binding is quite extensive and has a lot of possible solutions. both correct and not very good, depending on the problem being solved.