Steve
Steve

Reputation: 5073

How to reuse DataTable for different data source in C#?

I have a DataTable (displayed via a DataGridView) and want to reuse it to manually fill in different data. So the workflow is:

Every time I need to refill the DataTable, I do:

  1. Unhook the DataTable from the DataGridView.
  2. Clear DataTable content.
  3. Manually add DataColumns and DataRows to the DataTable.
  4. Hook the DataTable again with the DataGridView.

To achieve step 0, I simply do: DataGridView.DataSource = null.

To achieve step 1, I call DataTable.Clear(), DataTable.Rows.Clear() and DataTable.Columns.Clear().

To achieve step 3, I call DataGridView.DataSource = DataTable.

Step 2 is done in normal way and I skip the code.

Whenever the DataGridView is updated with a new content, if I click DataGridView column to sort, the next time when the DataTable is updated, I will get a null reference exception in step 2 when I try to add new rows. But if I never click DataGridView column to sort, all works fine.

I guess it has something to do with the sorting. But I have no idea what causes the null reference exception. Is it possible that the DataTable tries to search some keys in old content but couldn't find it? It cannot find the old content because of step 1 of course. What is the right way of clearing old DataTable content so it never refers the old content when I fill in new stuff?

Thanks.

Upvotes: 1

Views: 2552

Answers (1)

SLaks
SLaks

Reputation: 887777

The DataGridView's databinding is tied to the table (through a DataView); you cannot pull the table out from under it and expect it to continue working.
When you sort by a column, the grid asks the DataView to change its sort order, which fails because the column doesn't exist anymoe.

You should create a new DataTable.

Upvotes: 5

Related Questions