Binding List to DataGridView in WinForm
I have a class
class Person{
public string Name {get; set;}
public string Surname {get; set;}
}
and a List<Person> to which I add some items. The list is bound to my DataGridView.
List<Person> persons = new List<Person>();
persons.Add(new Person(){Name="Joe", Surname="Black"});
persons.Add(new Person(){Name="Misha", Surname="Kozlov"});
myGrid.DataSource = persons;
There is no problem. myGrid displays two rows, but when I add new items to my persons list, myGrid does not show new updated list. It only shows the two rows which I added before.
So what is the problem?
Rebinding every time works well. But when I bind a DataTable to the grid when every time when I make some changes to DataTable there is not any need to ReBind myGrid.
How to solve it without rebinding every time?
List does not implement IBindingList so the grid does not know about your new items.
Bind your DataGridView to a BindingList<T> instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
But I would even go further and bind your grid to a BindingSource
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
Every time you add a new element to the List you need to re-bind your Grid. Something like:
List<Person> persons = new List<Person>();
persons.Add(new Person() { Name = "Joe", Surname = "Black" });
persons.Add(new Person() { Name = "Misha", Surname = "Kozlov" });
dataGridView1.DataSource = persons;
// added a new item
persons.Add(new Person() { Name = "John", Surname = "Doe" });
// bind to the updated source
dataGridView1.DataSource = persons;
After adding new item to persons add:
myGrid.DataSource = null;
myGrid.DataSource = persons;
Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.
Pretty Simple example is available here,
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
참고URL : https://stackoverflow.com/questions/16695885/binding-listt-to-datagridview-in-winform
'developer tip' 카테고리의 다른 글
| Nullable vs. int? - Is there any difference? (0) | 2020.09.21 |
|---|---|
| How to Add a Dotted Underline Beneath HTML Text (0) | 2020.09.21 |
| How to make firefox headless programmatically in Selenium with python? (0) | 2020.09.21 |
| Inspecting standard container (std::map) contents with gdb (0) | 2020.09.21 |
| Java Thread Garbage collected or not (0) | 2020.09.21 |