Friday, December 2, 2016

AllowUsersToAddRows in DataGridView not working if DataSource is List<T>

Greetings!
Going back to a previous project of mine, I found out that some DataGridView control's DataSource where set using List<T> and as a result, prevented the users to add new data to the DataGridView.
private void List()
{
 List<Item> list = new List<Item>();
 for (int i = 0; i < 100; i++)
 {
  list.Add(new Item() { ID = i, Name = String.Format("{0}:{1}", "Test", i.ToString()) });
 }

 DataGridView1.DataSource = list;
}
The common solution is to use DataTable as the DataSource but if we want to use a List type object, we could use BindingList<T> or BindingSource. Both of these have AllowNew property which indicates that you can add items to the list using the AddNew() method. It is stated in DataGridView.AllowUsersToAddRows that "If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.".Well, List<T> does not implement IBindingList while BindingSource and BindingList implements this interface.
private void BindingList()
{
 BindingList<Item> list = new BindingList<Item>();
 for (int i = 0; i < 100; i++)
 {
  list.Add(new Item() { ID = i, Name = String.Format("{0}:{1}", "Test", i.ToString()) });
 }

 DataGridView1.DataSource = list;
}

0 comments:

Post a Comment