简体   繁体   中英

“No row can be added to a DataGridView control that does not have columns. Columns must be added first.” when DataGridView used with DataSource

I'm getting this error message ("No row can be added to a DataGridView control that does not have columns. Columns must be added first.") but I can't see anything wrong with my code. I swear I've done this hundreds of times but something is wrong.

class ViewItem {
   public string Name;
   public string Value;
}

...
BindingList<ViewItem> list=  new BindingList<ViewItem>();
dataGridView.DataSource = list;
ViewItem vi = new ViewItem(){Name = "Foo", Value = "Bar"};
list.Add(vi);
/// error here !

The columns need to be declared as Properties and not just data members. Add {get;set;} to the class members that you want to appear as Columns in the data grid.

class ViewItem {
   public string Name { get;set;}
   public string Value { get;set;}
}

...
BindingList<ViewItem> list=  new BindingList<ViewItem>();
dataGridView.DataSource = list;
ViewItem vi = new ViewItem(){Name = "Foo", Value = "Bar"};
list.Add(vi);
/// works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM