Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I'm getting this error when deleting a row in DataGridView control?

Tags:

c#

winforms

Why I'm getting this error when deleting a row in DataGridView control? How can I address this issue?

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);
        }
    }
like image 705
yonan2236 Avatar asked Dec 06 '11 04:12

yonan2236


2 Answers

List<T> does not implement IBindingList,

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

You need to use a class that implements IBindingList

Use a BindingList<T> or DataTable instead

like image 175
Ranhiru Jude Cooray Avatar answered Nov 17 '22 05:11

Ranhiru Jude Cooray


You have to remove an element from the person list.

person.RemoveAt(0);
like image 3
KV Prajapati Avatar answered Nov 17 '22 04:11

KV Prajapati