2013-08-28 156 views
4

我正在使用Winforms DevExpress,并将DataTable绑定到DataGridView工作正常。我遇到的问题是,我有一些函数将构建一个新的DataTable对象,它与原始数据表单独立,需要替换绑定到DataGridView的原始DataTable。DataGridView数据源不更新

DataTable originalTable = new DataTable("OriginalTable"); 

//Populate originalTable 

myDataGridControl.DataSource = originalTable; 

,一切工作正常与上面的代码,但下面的代码创建一个新的DataTable,需要设置为数据源的myDataGridControl。

DataTable newTable = new DataTable("NewTable"); 

//Populate newTable 

//Set newTable as the DataSource for myDataGridControl 
myDataGridControl.DataSource = newTable; 

我尝试了几个不同的尝试,例如调用RefreshDataSource(),Refresh(),将DataSource设置为null。我还没有得到它的工作。我该怎么做呢?

+0

的winform或WPF? – Aron

+0

winforms ...对不起,不提。 – TheJediCowboy

回答

4

有你试过以下组合?:

myDataGridControl.DataSource = originalTable; 
myDataGridControl.DataSource = null; 
myDataGridControl.DataSource = newTable; 

以我的经验,设置DataSourcenull然后到第二个来源是卓有成效的。

+2

这实际上是我尝试使它工作的第一次尝试,但不幸的是它并没有改变它。这在过去也适用于我。 – TheJediCowboy

8

尝试使用BindingSource,像这样:当你要重新绑定

DataTable sourceTable = new DataTable("OriginalTable"); 
BindingSource source = new BindingSource(); 
source.DataSource = sourceTable; 
myDataGridControl.Datasource = source; 

现在,更新sourceTable变量,就像这样:

sourceTable = new DataTable("NewTable"); 

// If the structure of `OriginalTable` and `NewTable` are the same, then do this: 
source.ResetBindings(false); 

// If the structure of `OriginalTable` and `NewTable` are different, then do this: 
source.ResetBindinds(true); 

注:阅读BindingSource.ResetBindings Method了解更多信息约ResetBindings()

+0

我尝试了这一点,它似乎并没有工作。不知道为什么这不起作用。 – TheJediCowboy

+0

这似乎是更新行,但列不更新。我已经验证列实际上在sourceTable中,但它们没有在网格控件上显示更改。 – TheJediCowboy

0

有点古老的话题,但既然它搞砸了我,我决定分享我的经验...... 绑定源并没有为我工作,Datagridview没有“MainView”变量。

我怀疑这个问题发生了,在我的情况下,运行排序命令后:

MyDataTable.DefaultView.Sort = "Column Asc"; 
MyDataTable = MyDataTable.DefaultView.ToTable(); 

我的解决办法后执行的操作再次重新绑定:

myDataGrid.DataSource = MyDataTable;