I want to put temporary datas into a generic list and bind it to the datagridview.
However, I can only put 1 row in the datagridview, I want to input multiple rows just like a database.
Here’s what I’ve tried, please tell me how to fix it. thanks :))
MyClass
{
private List<object> _list = new List<object>();;
public MyClass()
{
}
protected void OnClickButton(object sender, args e)
{
_list.Add(new { Name = textBoxName.Text, Gender = genderComboBox.Text });
dataGridView1.DataSource = _list;
}
}
Thank you very much! I’m really STUCK-overflow with this problem.
You could use
BindingList<object>instead ofList<object>, e.g. :The problem with your code is that you’re adding an element to
_listand then you pass the list as datasource of the grid.The first time everything works fine. The next times it doesn’t work because
DataGridView.DataSourceproperty internally performs a check that verify if the passed object is equal (or better reference-equal) to the current, and in case it does nothing.BindingList<T>works, because it exposes events (used internally by the grid) reporting when the list is modified, so basically you could also avoid to pass it to theDataSourceevery time except the first one.As a side note, I suggest you to use a specific class (as shown in @Alex answer) instead of put an anonymous-class in a list of
object.For example using a custom class like
Person, you can pass an emptyBindingList<Person>togrid.DataSourcethen add otherPersonobjects without any problems.Instead, you can’t pass an empty
BindingList<object>togrid.DataSourcebecause it results in a no-columns grid and so after you cannot add any elements having public properties (because the public properties are turned into columns). Thus, you need to pass aBindingList<object>with at least one object defined, such that the grid can understand what the columns will be and create them.