为什么我在删除DataGridView控件中的行时出现此错误?

yon*_*236 8 c# winforms

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

Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion.
Run Code Online (Sandbox Code Playgroud)
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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ran*_*ray 16

List<T>没有实现IBindingList,

public class List<T> : IList<T>, ICollection<T>, 
    IEnumerable<T>, IList, ICollection, IEnumerable
Run Code Online (Sandbox Code Playgroud)

您需要使用实现的类 IBindingList

使用BindingList<T>DataTable代替