We can use the SelectionChanged
event of the DataGridView
to track the selected row. The problem is when rebinding the datasource the CurrentRow.Index
is reset to zero.
We can handle this by detaching from the SelectionChanged
event before binding our datasource and re-attaching to the event after binding our datasource.
// Detach Event
dataGridView1.SelectionChanged -= dataGridView1_SelectionChanged;
// Bind Data
bindingSource.DataSource = data; // or dataGridView1.DataSource = data;
// Set Selected Row
dataGridView1.Rows[LastSelectedRowIndex].Selected = true;
// Re-attach Event
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
The event to track the selected index is simple.
int LastSelectedRowIndex = 0;
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
LastSelectedRowIndex = dataGridView1.CurrentRow.Index;
}
This is to give you an idea of the concept.
Maintain selection with a unique key value
Generally when we are rebinding information to a datasource this is because the information has changed. If the size of the dataset has changed this means that your row indexes will also change.
This is why we should not rely on LastSelectedRowIndex
for maintaining the selected row. Instead we should use a unique key in the datasource.
Our SelectionChanged
event becomes the following.
// KeyIndex is the Unique Key column within your dataset.
int KeyIndex = 2;
string LastSelectedKey = string.Empty;
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
LastSelectedKey = dataGridView1.CurrentRow.Cells[KeyIndex].Value.ToString();
}
And instead of setting the DataGridView
selected row by index, we can set it by our key value.
// Set Selected Row
// If we need to scroll the selected row into view
// this would be a good place to set FirstDisplayedScrollingRowIndex
foreach (DataGridViewRow row in dataGridView1.Rows)
if (row.Cells[KeyIndex].Value.ToString() == LastSelectedKey)
row.Selected = true;