Ayman Ayman - 18 days ago 5
C# Question

Move the focus to a DataGridView Cell - Finding the cell based on some value

How can I move the focus to a cell and highligh it based on text box value for example text box value.

The below code is used based on number of cell but I am looking for to select entered value in text box.

dgpay.CurrentCell = dgpay.Rows[2].Cells[0];
dgpay.Rows[2].Selected = true;

Answer

You need to set CUrrentCell first, then call BeginEdit by passing true as parameter to put the current cell in edit mode and select all the cell's contents. For example:

this.dataGridView1.CurrentCell = this.dataGridView1.Rows[2].Cells[0];
this.dataGridView1.BeginEdit(true);

Note: For example if you want to find the first cell in DataGridView based on some value and select the cell and begin editing you can use such code:

var cell = dataGridView1.Rows.Cast<DataGridViewRow>()
                .SelectMany(x => x.Cells.Cast<DataGridViewCell>())
                .Where(x => string.Format("{0}", x.FormattedValue) == textBox1.Text)
                .FirstOrDefault();
if (cell != null)
{
    this.dataGridView1.CurrentCell = cell;
    this.dataGridView1.BeginEdit(true);
}