簡體   English   中英

當控件是集合數據源上的數據綁定錯誤時,不能以編程方式將行添加到DataGridView的rows集合中

[英]Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound error on collection data source

我知道有關於此錯誤的線程,但是我只在數據源是表的情況下找到了解決方案。 就我而言,數據源是一個列表。 這是我的代碼:

    private void AdminForm_Load(object sender, EventArgs e)
    {
        dgUser.DataSource = read.getUsers();
        dgUser.Rows.Add();
    }

因此,顯然Add()方法不適用於集合。 有什么辦法嗎?

List<String> list = new List<String>();
list.add("val1");
dataGridView1.DataSource = list;
list.add("val2");
dataGridView1.DataSource = null;
dataGridView1.DataSource = list;

在這種情況下,您必須將數據源設置為null,然后再次將其設置為list; 或者更好地使用綁定列表

BindingList <String> list = new BindingList<String>();
list.Add("val1");
dataGridView1.DataSource = list;
list.Add("val1");

在這種情況下,您不必“刷新”任何內容,它會自動完成

請嘗試以下代碼。 另外,您可以在第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;
}
   var dataSource = datagrid.DataSource;
                    (dataSource as IList).Add(obj);
                    datagrid.DataSource = null;
                    datagrid.DataSource = dataSource;
                    datagrid.Refresh();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM