为什么我'm得到这个错误时,删除一行在DataGridView控件

本文关键字:删除 控件 DataGridView 一行 错误 为什么 | 更新日期: 2023-09-27 18:16:48

为什么在DataGridView控件中删除一行时会出现此错误?如何解决这个问题?

Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion.

public partial class Form1 : Form
    {
        List<Person> person = new List<Person>();
        public Form1()
        {
            InitializeComponent();
        }
        void Form1Load(object sender, EventArgs e)
        {
            person.Add(new Person("McDonalds", "Ronald"));
            person.Add(new Person("Rogers", "Kenny"));          
            dataGridView1.DataSource = person;
        }
        void BtnDeleteClick(object sender, EventArgs e)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
        }
    }

为什么我'm得到这个错误时,删除一行在DataGridView控件

List<T>不实现IBindingList

public class List<T> : IList<T>, ICollection<T>, 
    IEnumerable<T>, IList, ICollection, IEnumerable

您需要使用实现IBindingList的类

BindingList<T>DataTable代替

您必须从person列表中删除一个元素。

person.RemoveAt(0);

我的解决方案:

void BtnDeleteClick(object sender, EventArgs e)
{
    person.RemoveAt(dataGridView1.SelectedRows[0].Index);
}