user2809386
user2809386

Reputation:

set selected row datagridview by cell's value

how to set selected row on dataGridView by a string?

example..

enter image description here

when form_loaded...i want that dataGridView with cell "LSN" is selected

so if i have a string text = "LSN"

then that table's row with cell value "LSN" is selected..

i usually use dataGridView1.Rows[3].Selected = true; to set selected row in datagridview..

but how can i do that if i dont know row's index and only know a string ?

Upvotes: 3

Views: 20632

Answers (3)

Siva Sankar Gorantla
Siva Sankar Gorantla

Reputation: 562

Please try below code...

string txtSearchValue="LSN";
int rowIndex = -1; 

DataGridViewRow row = dgv.Rows.Cast<DataGridViewRow>()
    .Where(r=>r.Cells["SystemId"].Value.ToString().Equals(txtSearchValue))
    .First();
rowIndex = row.Index; 

dataGridView1.Rows[rowIndex].Selected = true;

without LINQ:

foreach(DataGridViewRow row in DataGridView1.Rows)
{
    if(row.Cells[1].Value.ToString().Equals(txtSearchValue))
    {
        rowIndex = row.Index;
        break;
    }
}

Upvotes: 4

Equalsk
Equalsk

Reputation: 8194

You would have to iterate through each row of the DataGridView until you find the value you want. You can then select the row and break out of the loop.

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    // 0 is the column index
    if (row.Cells[0].Value.ToString().Equals("LSN"))
    {
        row.Selected = true;
        break;
    }
}

I haven't tested this example but it should give you the right idea.

Upvotes: 4

code
code

Reputation: 1137

Linq maybe?

How can I use LINQ to find a DataGridView row?

dataGridView1.Rows

dataGridView1.Rows.Cast<DataGridViewRow>().Where(x => x.Kode == "LSN").FirstorDefault()

Upvotes: 1

Related Questions