Lukas Lukas - 1 year ago 354
C# Question

Find a row in dataGridView based on column and value

I have a dataGridView that has 3 columns: SystemId, FirstName, LastName that is bound using database information. I would like to highlight a certain row, which I would do using:

dataGridView1.Rows[????].Selected = true;

The row ID I however do not know and the bindingsource keeps changing, thus row 10 could be "John Smith" in one instance but not even exist in another (I have a filter that filters out the source based on what user enters, so typing in "joh" would yield all rows where first / last name have "joh" in them, thus my list can go from 50 names to 3 in a click).

I want to find a way how I can select a row based on SystemId and a corresponding number. I can get the system ID using the following method:

systemId = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["SystemId"].Value.ToString();

Now I just need to apply it to the row selector. Something like dataGridView1.Columns["SystemId"].IndexOf(systemId} but that does not work (nor does such method exist). Any help is greatly appreciated.

Answer Source

This will give you the gridview row index for the value:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
        rowIndex = row.Index;

Or a LINQ query

int rowIndex = -1;

        DataGridViewRow row = dgv.Rows
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))

        rowIndex = row.Index;

then you can do:

dataGridView1.Rows[rowIndex].Selected = true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download