【问题标题】:Why I'm getting this error when deleting a row in DataGridView control?为什么在 DataGridView 控件中删除一行时出现此错误?
【发布时间】:2011-12-06 18:41:53
【问题描述】:

为什么在 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);
        }
    }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    List&lt;T&gt; 没有实现IBindingList

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

    你需要使用实现IBindingList的类

    改用BindingList&lt;T&gt;DataTable

    【讨论】:

    • 所以不是 List,我是否必须将其设为 BindingList
    • 谢谢你和谷歌。现在刚刚遇到这个错误:)
    • 非常感谢您提供这个救命稻草的答案。
    【解决方案2】:

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

    person.RemoveAt(0);
    

    【讨论】:

      【解决方案3】:

      我的解决方案:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多