John Deck
John Deck

Reputation: 899

How to focus a specific row in datagridview based on value in textbox?

I have a datagridview dgPersons which content binds from database (Columns : idPerson, personName) .. in the same form I have textboxes txtCodePerson ,txtPersonName

I add data to the database by filling the textboxses and click on btnSave .. then re pind the data to make the new row visible on the datagridview

Now .. I want to focus on the row which I recently add by get the value from txtCodePerson and set the selected row which equal that value in idPerson Column

Code :

String searchValue = txtCodePerson.Text;
dgPersons.ClearSelection();
int rowIndex = -1;
foreach (DataGridViewRow row in dgPersons.Rows)
{
 if (row.Cells[0].Value.ToString().Equals(searchValue))
  {
    rowIndex = row.Index;
    break;
  }
}

But it didn't work .. after adding a row the selected row automatically go to the first row

Notice : selecting the last row will not do what I want because the datagridview data resorted alphabitcally on personName column after binding data

Upvotes: 1

Views: 2646

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125342

You can find the row that its corresponding column value equals to the specified text. Then set it as current row.

For example, if you are looking for the row that its idPerson column equals to the text of txtCodePerson, then you can use following code:

var searchValue = txtCodePerson.Text;    
var row = dataGridView1.Rows.Cast<DataGridViewRow>()
    .Where(x => !x.IsNewRow)
    .Where(x => ((DataRowView)x.DataBoundItem)["idPerson"].ToString().Equals(searchValue))
    .FirstOrDefault();
this.dataGridView1.CurrentCell = row.Cells[0];

Upvotes: 3

Related Questions