datagrid changing datasource at runtime not working 2nd time

I need to display results of different queries into the same datagrid. The query results are from the same table and go into the same dataset. I can only display to the datagrid the query results the very first time. After that I see no rows, though the columns are there. I make sure I clear the dataset of all rows and schema info and also remove all databinding from the datagrid before I repopulate the dataset and rebind to the grid. Note: The dataset contains the correct data and has the correct number of rows. It's the datagrid that does not display them. What's worth noting, is that if I create a new dataset each time the event handler is executed, it works. It's reusing the same dataset that causes problems. I need the dataset and the data it contains to persist past the lifetime of the event handler, so that is not a workable solution for my purposes. 


Here's the code (it's part of a click event handler). 
// all objects have been declared and instantiated at Form scope
private void btnFetchRows_Click(object sender, System.EventArgs e)
{
// this code works the first time it is execute, but not in subsequent times
      
      ds.Reset();
      int rows = 0;
     dataGrid.DataBindings.Clear();
     dataGrid.DataSource = null; // for extra measure, though it does not help!
     dataGrid.DataMember = "";

     dbAdapter.Fill(ds,"employee"); // works fine! rows are returned and have correct data
   
    //dataGrid.SetDataBinding(ds, "employee");
   // tried the above statement and the following two, no change in behavior
   // works only the first time the handler is executed
   dataGrid.DataSource = ds;
   dataGrid.DataMember = "employee"; 
}


Any advise will be greatly appreciated. Thanks!
- erika


Answer this question

datagrid changing datasource at runtime not working 2nd time

  • Muntaser

    First off, you want to remove bindings and of course set the datasource to null and the datamember = ""

    Then you will call the clear on the datatable to clear all rows and then you will fill it and then you will reset the databindings

    You know you don't have to do that SetDataBinding and all that  when you do
    datasource = ds
    datamember = "employee" 

    It will auto create the binding.

    It's mainly an order of events issue.

  • Danny Vucinec

    Thanks for your help though. It works if you bind directly to the datatable, but it does not work when bound to the dataset. In our application we do not want to expose the particulars of a dataset (which we encapsulate) to the UI so working with tables directly does not fit with our architecture. I found if I fill the schema first and then fill the rows that I can then do the databinding as expected. Knowledge base article KB - 318607 mentions other workarounds.
  • datagrid changing datasource at runtime not working 2nd time