2011-12-06 50 views
8

Tại sao tôi nhận được lỗi này khi xóa một hàng trong điều khiển DataGridView? Tôi làm cách nào để giải quyết vấn đề này?Tại sao tôi nhận được lỗi này khi xóa một hàng trong điều khiển 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); 
     } 
    } 

Trả lời

14

List<T> không thực hiện IBindingList,

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

Bạn cần phải sử dụng một lớp mà thực hiện IBindingList

Sử dụng một BindingList<T> hoặc DataTable thay

+0

nên thay vì Danh sách , tôi phải làm cho nó một cái gì đó BindingList ? – yonan2236

+0

Có. Cần làm việc. –

+0

Cảm ơn bạn và Google. Chỉ cần chạy vào lỗi này ngay bây giờ :) – Latheesan

2

Bạn phải xóa một phần tử khỏi danh sách person.

person.RemoveAt(0); 
0

Giải pháp của tôi:

void BtnDeleteClick(object sender, EventArgs e) 
{ 
    person.RemoveAt(dataGridView1.SelectedRows[0].Index); 
} 
Các vấn đề liên quan