CJ7
CJ7

Reputation: 23275

How to handle refreshing of parent windows?

I have a form which can cause another form to show.

The Activated event on the first form currently refreshes a DataGridView.

How can I preserve the row selection on the DataGridView? The refreshing of the DataGridView causes the first row to be selected.

The data in the DataGridView is refreshed by the following:

MyDataGridView.DataSource = getDataTableFromDb();

where getDataTableFromDb() returns a DataTable.

Upvotes: 0

Views: 88

Answers (1)

David Hall
David Hall

Reputation: 33153

To resolve this you will probably need a BindingSource - not a problem since there isn't really any reason not to have one.

You can simply drag the BindingSource control onto the design surface of the form, just as any other control.

Then you make the DataTable the data source for the binding source and make the binding source the data source for the grid.

The code to set up a binding source is very simple:

bindingSource1.DataSource = getDataTableFromDb();
MyDataGridView.DataSource = bindingSource1;

This might be enough to solve your problem. (I've seen it work in certain scenarios)


If the position is still not being maintained then with the binding source you can now use the Find and Position members.

First - just before you rebind you need to grab some unique piece of information about the currently selected item. Usually the primary key from the database.

You can get this from the binding source's Current property, something like:

DataRowView r = bs.Current as DataRowView;
var id = int.Parse(r.Row.ItemArray[0].ToString());

Then with this id, after you rebind the grid, have something like:

int index = bs.Find("CustomerId", 3);
bs.Position = index;

The "CustomerId" property above is the name property representing of the primary key column you use - in the data table.


One important thing to note is that this only works because your data source - the DataTable supports Find out of the box. If you change to something like a BindingList you will need to implement the FindCore members yourself.

Upvotes: 1

Related Questions