Reputation: 533
I know there are threads on this error but i only found solutions in case the data source is a table. In my case the data source is a list. Here is my code:
private void AdminForm_Load(object sender, EventArgs e)
{
dgUser.DataSource = read.getUsers();
dgUser.Rows.Add();
}
So apparently the Add() method doesn't work for collections. Any solutions?
Upvotes: 1
Views: 5343
Reputation: 167
var dataSource = datagrid.DataSource;
(dataSource as IList).Add(obj);
datagrid.DataSource = null;
datagrid.DataSource = dataSource;
datagrid.Refresh();
Upvotes: 0
Reputation: 119
List<String> list = new List<String>();
list.add("val1");
dataGridView1.DataSource = list;
list.add("val2");
dataGridView1.DataSource = null;
dataGridView1.DataSource = list;
In this case you have to set datasource to null, and then again to list; Or better to use Binding list
BindingList <String> list = new BindingList<String>();
list.Add("val1");
dataGridView1.DataSource = list;
list.Add("val1");
In this case you dont have to "refresh" anything, its done automatically
Upvotes: 2
Reputation: 300
Try code below. Additional you can check collection type in line 4.
private bool AddNewRow(DataGridView grid)
{
var collection = grid.DataSource;
if (collection == null)
{
grid.Rows.Add();
return true;
}
var itemType = GetCollectionItemType(collection.GetType());
if (itemType != null && itemType != typeof(object) && !itemType.IsAbstract && itemType.GetConstructor(Type.EmptyTypes) != null)
{
try
{
dynamic item = Activator.CreateInstance(itemType);
((dynamic)collection).Add(item);
if (!(collection is System.ComponentModel.IBindingList))
{
grid.DataSource = null;
grid.DataSource = collection;
}
return true;
}
catch { }
}
return false;
}
public static Type[] GetGenericArguments(this Type type, Type genericTypeDefinition)
{
if (!genericTypeDefinition.IsGenericTypeDefinition)
return Type.EmptyTypes;
if (genericTypeDefinition.IsInterface)
{
foreach (var item in type.GetInterfaces())
if (item.IsGenericType && item.GetGenericTypeDefinition().Equals(genericTypeDefinition))
return item.GetGenericArguments();
}
else
{
for (Type it = type; it != null; it = it.BaseType)
if (it.IsGenericType && it.GetGenericTypeDefinition().Equals(genericTypeDefinition))
return it.GetGenericArguments();
}
return new Type[0];
}
public static Type GetCollectionItemType(Type collectionType)
{
var args = GetGenericArguments(collectionType, typeof(IEnumerable<>));
if (args.Length == 1)
return args[0];
return typeof(IEnumerable).IsAssignableFrom(collectionType)
? typeof(object)
: null;
}
Upvotes: 0