user361108
user361108

Reputation: 69

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?

Upvotes: 7

Views: 33452

Answers (4)

Jayadev
Jayadev

Reputation: 1

//If U Have Add CheckBox To Ur Datagridview
int rowIndex = -1;
DataGridViewCheckBoxCell oCell;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    oCell = row.Cells[0] as DataGridViewCheckBoxCell;
    bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
    if (true == bChecked)
    {
        rowIndex = row.Index;
       //ur code
    }
}

Upvotes: 0

openshac
openshac

Reputation: 5165

From: http://www.vbforums.com/showthread.php?t=610134

Call the Find method of the BindingSource and it will return the index of the matching row if there is one. If there is, you index the BindingSource to get that row and update the appropriate fields. If there isn't, you call the AddNew method of the BindingSource to create a new row and set the appropriate fields.

Upvotes: 0

Pavel Belousov
Pavel Belousov

Reputation: 1858

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;

Upvotes: 18

Hans Olsson
Hans Olsson

Reputation: 55039

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

Upvotes: 1

Related Questions