使DataGridView可视化地反映其DataSource中的更改的正确方法

假设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 。 但这似乎很奇怪。 我相信还有其他几种方法。 但是,正确的官方方式是什么?

正确的方法是数据源实现IBindingList ,对SupportsChangeNotification返回true ,并发出ListChanged事件。 但是,AFAIK, DataView 这样做……

我很确定如果您将DataGridView绑定到DataTable的DefaultView,并且Table更改,则更改会自动反映在DataGridView中。 你试过这个并且有问题吗? 发布您更新DataTable的代码,可能还有其他错误。 事实上,这是我刚刚写的一个小样本应用程序:

 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本身添加另一行。 我测试了它,果然它出现在网格中没有任何问题。