0

I have a TextBox named txtvalue.
Then I have a DataGridView with a column named Id.
My problem is how to set the row of the DataGridView selected by value of txtvalue equal with column ID.
The text in textbox is not number, i just want it equal to column "ID" in DataGridView.
I know this way to set that but it so long, is there any fast way to get shorter not use Linq?

Foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Columns["Id"].Value.ToString().Equals(txtvalue.Text))
    {
        row.Selected = true;
        break;
    }
}

I want to have fast way without use loop? Any idea please? The value of Columns "ID" of Datagridview is:
----- ID -----
   abc
   xyz
   klm
   mnz
 bla...bla
So the value is not the number. and the textbox value is equal with that

Jacky Euro
  • 69
  • 1
  • 8

1 Answers1

0

There is a indexer on DataGridView.Rows

Therefore you just have to convert your string to a int and access the index of the row to set selected:

dataGridView1.Rows(Int32.Parse(txtvalue.Text )).Selected = True

Be aware that there is no check and the Int32.Parse method could throw an exception Better solution would be something like that:

int index;
bool parsed = Int32.TryParse(txtvalue.Text, out index);
if (parsed)
{
  dataGridView1.Rows(index).Selected = True
}
Cedric Mendelin
  • 172
  • 1
  • 2
  • 9
  • U don't understand what i said: i not mean the value in textbox is number so we can convert like that – Jacky Euro Sep 26 '18 at 11:15
  • Therefore I dont understand the question in general. Can you give any further clarification? What is the value of the Textbox then? Or do you want to have the row selected by the value of the textbox itself? Than I would go for a TextChanged (https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.textchanged?redirectedfrom=MSDN&view=netframework-4.7.2) Event and select the Row by the line given above. – Cedric Mendelin Sep 26 '18 at 15:09
  • Value of the textbox is qual with value of Columns ID in datagridview. – Jacky Euro Sep 27 '18 at 06:44
  • Ah now I got it. There are many solution in this article: https://stackoverflow.com/questions/10179223/find-a-row-in-datagridview-based-on-column-and-value – Cedric Mendelin Sep 27 '18 at 07:14
  • I know that, in my topic, i use for loop. But the way i want is i want directly. Any way to do that? – Jacky Euro Sep 27 '18 at 08:15