【问题标题】:Correct way to have a DataGridView visually reflect changes in its DataSource让 DataGridView 直观地反映其 DataSource 更改的正确方法
【发布时间】:2009-03-10 14:06:31
【问题描述】:
假设DataGridView 将其DataSource 属性设置为DataView 实例。
DataGridView dgv;
DataTable dt;
// ... dt gets populated.
DataView dv = dt.DefaultView;
dgv.DataSource = dv;
// ... dt gets modified
// The DataGridView needs to update to show these changes visually
// What goes here?
我知道你可以将dgv.DataSource 设置为null,然后再设置回dv。但这似乎很奇怪。我敢肯定还有其他几种方法。但是,正确的官方方法是什么?
【问题讨论】:
标签:
c#
winforms
ado.net
datagridview
【解决方案1】:
正确的方式是数据源实现IBindingList,为SupportsChangeNotification返回true,并发出ListChanged事件。但是,AFAIK,DataView 确实 这...
【解决方案2】:
我很确定,如果您将 DataGridView 绑定到 DataTable 的 DefaultView,并且 Table 发生更改,则更改会自动反映在 DataGridView 中。你试过这个并且遇到问题吗?发布更新数据表的代码,也许还有其他问题。事实上,这是我刚刚写的一个小示例应用程序:
public partial class Form1 : Form
{
private DataTable table;
public Form1()
{
InitializeComponent();
table = new DataTable();
this.LoadUpDGV();
}
private void LoadUpDGV()
{
table.Columns.Add("Name");
table.Columns.Add("Age", typeof(int));
table.Rows.Add("Alex", 27);
table.Rows.Add("Jack", 65);
table.Rows.Add("Bill", 22);
table.Rows.Add("Mike", 36);
table.Rows.Add("Joe", 12);
table.Rows.Add("Michelle", 43);
table.Rows.Add("Dianne", 67);
this.dataGridView1.DataSource = table.DefaultView;
}
private void button1_Click(object sender, EventArgs e)
{
table.Rows.Add("Jake", 95);
}
}
基本上,当表单加载时,它只是在表格中填充姓名和年龄。然后它将它绑定到 DGV。单击按钮时,它会向 DataTable 本身添加另一行。我对其进行了测试,果然它毫无问题地出现在网格中。