【问题标题】:DataGridView DataSource Not UpdatingDataGridView 数据源未更新
【发布时间】:2013-08-30 23:25:56
【问题描述】:

我正在使用 Winforms DevExpress,我正在将一个 DataTable 绑定到一个运行良好的 DataGridView。我遇到的问题是我有一些函数将构建一个新的 DataTable 对象,该对象与需要替换绑定到 DataGridView 的原始 DataTable 的原始对象分开。

DataTable originalTable = new DataTable("OriginalTable");

//Populate originalTable 

myDataGridControl.DataSource = originalTable;

上面的代码一切正常,但是下面的代码创建了一个新的 DataTable 并且需要设置为 myDataGridControl 的 DataSource。

DataTable newTable = new DataTable("NewTable");

//Populate newTable

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

我已经尝试了几种不同的尝试来完成这项工作,例如调用 RefreshDataSource()、Refresh()、将 DataSource 设置为 null。我还没有让它工作。我该怎么做?

【问题讨论】:

  • winforms...抱歉没有提及。

标签: c# winforms data-binding datatable devexpress


【解决方案1】:

有点老话题,但因为它困扰我,我决定分享我的经验...... 绑定源对我不起作用,Datagridview 没有“MainView”变量。

我怀疑问题是在运行排序命令后发生的:

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

我的解决方案是在执行操作后再次重新绑定:

myDataGrid.DataSource = MyDataTable;

【讨论】:

    【解决方案2】:

    如果有人在尝试其他建议后仍遇到问题,那么对 GridControl.MainView 属性的以下调用 PopulateColumns() 为我解决了问题。

    例如:

    myDataGridControl.MainView.PopulateColumns();
    

    这也可以参考下面的 DevExpress 文章。 http://www.devexpress.com/Support/Center/Question/Details/Q362978

    【讨论】:

      【解决方案3】:

      尝试使用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() 的更多信息。

      【讨论】:

      • 我试过这个,但它似乎不起作用。不知道为什么这不起作用。
      • 这似乎是在更新行,但列没有更新。我已经验证了这些列实际上在 sourceTable 中,但它们没有显示网格控件上的更改。
      【解决方案4】:

      您尝试过以下组合吗?:

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

      根据我的经验,将 DataSource 设置为 null 然后设置为第二个源就可以了。

      【讨论】:

      • 这实际上是我第一次尝试让它工作,但不幸的是它并没有改变它。这在过去也对我有用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 2017-05-27
      • 2019-03-14
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多