Ayman Ayman - 5 months ago 26
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;


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];

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)
if (cell != null)
    this.dataGridView1.CurrentCell = cell;