Home c# Can't add a new row to the DataGridView?

Can’t add a new row to the DataGridView?

Author

Date

Category

How do I fix this? I want to add a blank line at the end.

 enter image description here

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:

  1. Instead of the local variable DataSet ds , use a private form field such as private DataTable Trains (you only have one table) so that it can be accessed from any method forms.

  2. Fill in the field and grid:

    string SqlText = "SELECT * FROM [Train]";
    SqlDataAdapter da = new SqlDataAdapter (SqlText, ConnStr);
    da.Fill (Trains);
    dataGridView1.DataSource = Trains;
    
  3. Add blank line to DataTable rebind data

    Trains.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:

  1. make a model class (conventionally Train ) with the required public properties.
  2. Fill model objects with the data obtained from the request.
  3. Collect the obtained objects into the BindingList collection, which we put in the DataGridView.DataSource .
  4. Add new blank objects to this collection.
  5. 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.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions