System.InvalidOperationException will be thrown if I call the method DataGridView.Rows.Add, How to r

R

Ryan

I want to programmatically add a row to DataGridView (a datasource was
binded with it), but when I call the method DataGridView.Rows.Add, a
System.InvalidOperationException will be thrown and the error message is:
Rows cannot be programmatically added to the DataGridView's rows
collection when the control is data-bound.

But if I create a DataGridView without any datasource binded, the method
DataGridView.Rows.Add can work normally.
I don't know the reason why?
 
M

Marc Gravell

Once bound, the UI is not the "master" of the data; instead, locate
your datasource, and ask *that* to add a record. This should (if the
appropriate interfaces are met) communicate back to the UI to say "a
change happened; update thyself".

How to do the add depends on your specific datasource.

Marc
 
R

Ryan

Thank you very much!

I can add row now!
DataTable dt = (DataTable)(BindingSource)DataGrideView.DataSource;
DataRow row = dt.NewRow();
row["name"] = "test";
dt.Rows.Add(row);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top