DataGridView DataSource Not Updating

隐身守侯 提交于 2021-02-08 13:52:49

问题


I am using Winforms DevExpress and I am binding a DataTable to a DataGridView which is working fine. The problem I am having is that I have some functions that will build a new DataTable object which is separate from the original which needs to replace the original DataTable that is bound to the DataGridView.

DataTable originalTable = new DataTable("OriginalTable");

//Populate originalTable 

myDataGridControl.DataSource = originalTable;

Everything works fine with the code above, but the following code creates a new DataTable and needs to be set as the DataSource for myDataGridControl.

DataTable newTable = new DataTable("NewTable");

//Populate newTable

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

I have tried several different attempts to make this work such as calling RefreshDataSource(), Refresh(), setting DataSource to null. I have not gotten it to work yet. How do I do this?


回答1:


Try using a BindingSource, like this:

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

Now when you want to re-bind, update the sourceTable variable, like this:

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);

Note: Read BindingSource.ResetBindings Method for more information about ResetBindings().




回答2:


Having you tried the following combination?:

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

In my experience, setting the DataSource to null then to the second source does the trick.




回答3:


In case anybody is having trouble even after trying the other suggestions, the following call to PopulateColumns() on the GridControl.MainView property solved the problem for me.

For example:

myDataGridControl.MainView.PopulateColumns();

This can also be referenced from the following article with DevExpress. http://www.devexpress.com/Support/Center/Question/Details/Q362978




回答4:


Kinda old topic, but since it bugged me, I decided to share my experience... Binding the source didn't work for me and Datagridview doesn't have "MainView" variable.

I suspect the issue happens, in my case, after running the sorting command:

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

My solution was to rebind again after actions performed:

myDataGrid.DataSource = MyDataTable;


来源:https://stackoverflow.com/questions/18478578/datagridview-datasource-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!