0

When my form first loaded, I use SqlDataAdapter.Fill to add a table into a DataSet.

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

Then I use a button which will change the query and update the Bus table:

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

But the data in DataGridView remains the same. What was happened and how can I fix it?

Ryan
  • 135
  • 9
  • is your DataSet not getting udpated? or DataGridView not reflecting updated datasource ? – Hari Prasad Sep 22 '15 at 03:46
  • How to check that? But I think DataSet is the problem, because when I change the table name to Bus2 in Finally block and change the DataMember of DataGridView to Bus2, it work as expected. – Ryan Sep 22 '15 at 03:52
  • Removing the table from the dataset might not "remove" it from the grid view (the table object still exists in memory, just not referenced by the dataset). I think you should be able to just clear the table, leave it in place and have the select command fill the existing table. I haven't done WinForms databinding in a while but you might then need to call some command like "DataBind()" or so for the grid view to refresh. In any case by keeping the existing table, the data source and member association by the grid view will remain the same. – Christoph Sep 22 '15 at 03:54

2 Answers2

0

Reset the datasource property again should do it:

this.bus_DataGridView.DataSource = this.bus_DataSet;
archangel76
  • 1,544
  • 2
  • 11
  • 18
0
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";
andy
  • 5,979
  • 2
  • 27
  • 49