[英]C#, add row to DataGridView
我有帶DataGridView和Button的窗體。 DataGridView顯示ArrayList中的數據,我想通過DataGridView將元素添加到ArrayList中。 因此,我正在嘗試:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = Student.students;
}
private void button1_Click(object sender, EventArgs e)
{
Student st = new Student();
Student.students.Add(st);
}
}
但這是行不通的……如何向該DataGridView添加新行? 謝謝。
列表未實現IBindingList,因此網格不知道您的新項目。
而是將您的DataGridView綁定到BindingList。
這是例子
你的班 ,
class Student
{
public int ID { get; set; }
public string Name { get; set; }
}
}
在后面的代碼中
BindingList<Student> STUDENTS;
public Form1()
{
InitializeComponent();
STUDENTS = new BindingList<Student>();
dataGridView1.DataSource = STUDENTS;
}
private void button1_Click(object sender, EventArgs e)
{
STUDENTS.Add(new Student { ID =1 , Name ="test" });
dataGridView1.DataSource = STUDENTS;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.