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?
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()
.