Donate

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;
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.