【问题标题】:How to remove a table in a DataSet and then add new table with the same name? (C# - Winforms)如何删除 DataSet 中的表,然后添加同名的新表? (C# - Winforms)
【发布时间】:2015-12-18 21:33:48
【问题描述】:

当我的表单首次加载时,我使用 SqlDataAdapter.Fill 将表添加到数据集中。

this.bus_SqlDataAdapter.SelectCommand.CommandText = "select * from Bus"
this.bus_SqlDataAdapter.Fill(this.bus_DataSet, "Bus");
this.bus_DataGridView.DataSource = this.bus_DataSet;
this.bus_DataGridView.DataMember = "Bus";

然后我使用一个按钮来更改查询并更新 Bus 表:

this.bus_SqlDataAdapter.SelectCommand.CommandText = "select * from Bus where ID = 1"
try
{
        this.bus_DataSet.Tables.Remove("Bus");
}
catch
{
        //Don't do anything
}
finally
{
        this.bus_SqlDataAdapter.Fill(this.bus_DataSet, "Bus");
}

但 DataGridView 中的数据保持不变。 发生了什么,我该如何解决?

【问题讨论】:

  • 您的数据集没有更新吗?还是 DataGridView 没有反映更新的数据源?
  • 如何检查?但我认为DataSet是问题所在,因为当我在Finally块中将表名更改为Bus2并将DataGridView的DataMember更改为Bus2时,它按预期工作。
  • 从数据集中删除表格可能不会从网格视图中“删除”它(表格对象仍然存在于内存中,只是没有被数据集引用)。我认为您应该能够只清除表格,将其留在原处并让 select 命令填充现有表格。我有一段时间没有完成 WinForms 数据绑定,但您可能需要调用一些命令,例如“DataBind()”,以便刷新网格视图。无论如何,通过保留现有表,网格视图的数据源和成员关联将保持不变。

标签: c# winforms ado.net


【解决方案1】:
if(SomeCondition)
{
 this.bus_SqlDataAdapter.SelectCommand.CommandText = "select * from Bus"
}
else
{
 this.bus_SqlDataAdapter.SelectCommand.CommandText = "select * from Bus  where ID = 1"
}
this.bus_SqlDataAdapter.Fill(this.bus_DataSet, "Bus");
this.bus_DataGridView.DataSource = this.bus_DataSet;
this.bus_DataGridView.DataMember = "Bus";

【讨论】:

    【解决方案2】:

    再次重置数据源属性应该这样做:

    this.bus_DataGridView.DataSource = this.bus_DataSet;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多