Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the row ID from datagridview, given a row value?

Can anyone help me please?

I have to find the row number from 1 selected array which I stored in one separate array and randomly I'm trying to get the row number from datagridview

In other words: if I know a column value for a given row in a datagridview (e.g. for this row, FirstName == 'Bud'), how can I get the row ID?

like image 373
user361108 Avatar asked Jun 08 '10 09:06

user361108


2 Answers

You can use LINQ query:

        int index = -1;

        DataGridViewRow row = dgv.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells[columnId].Value.ToString().Equals("Some string"))
            .First();

        index = row.Index;
like image 58
Pavel Belousov Avatar answered Sep 20 '22 05:09

Pavel Belousov


There's probably some easier way where you filter it in some way but at the moment I can only think of looping through it.

int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if(row.Cells(1).Value.ToString().Equals("mystr"))
    {
        rowIndex = row.Index;
        break;
    }
}
// rowIndex is now either the correct index or -1 if not found
like image 34
Hans Olsson Avatar answered Sep 20 '22 05:09

Hans Olsson