DataGridView - refresh data and select the same row you had before

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

I'd like to refresh my dataGridView and select the same row that was
previously selected. Unfortunately, the rows location may have changed
during the refresh. Assuming one field is unique and I've saved this value
prior to the refresh, do I have to iterate through all the records until I
find a match, or is there a method that will search for me?

Thanks in advance.

Mark
 
Hi Mark,

I don't know what data source you are using to bind to the data grid view.
But if you use BindingSource, you could call the Find method of the
BindingSource component to find the index of the row which has key value.
Then you could set the Position propery of the BindingSource to the index.

The following is a sample. This sample has a DataSet with a DataTable named
Persons in it (PersonID is the primary key) and a BindingSource component
and a DataGridView. I set bindingSource1.DataSource to dataSet11 and set
bindingSource1.DataMember to Persons and set dataGridView1.DataSource to
bindingSource1.

private void button1_Click(object sender, EventArgs e)
{
// get the value of the primary key before refresh the data in
the data source
DataRowView rowview =
this.dataGridView1.CurrentRow.DataBoundItem as DataRowView;
int personID = (int)rowview["PersonID"];

// refresh the data
DataSet1TableAdapters.PersonsTableAdapter personAdapter = new
DataGridViewSelectSameRow.DataSet1TableAdapters.PersonsTableAdapter();
personAdapter.Fill(this.dataSet11.Persons);

// restore the current row by the value of the primary key
int index = this.bindingSource1.Find("PersonID", personID);
this.bindingSource1.Position = index;
}

Hope this helps.
If you have anything unclear, please feel free to let me know.


Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top