Search for the first letter of a word using keyboard input in data grid view
My question is how to search for a word's start with a letter which is given by keyboard. I did this using the code below.
Now I want to do this for the next row. Once I find a word, I want to go to the next row by clicking the down arrow. But开发者_如何转开发 when I click the down arrow, the selected row goes to the previous selected row.
How can I solve this?
if (Char.IsLetterOrDigit(e.KeyChar))
{
if (Char.IsLetter(e.KeyChar))
{
for (int i = 0; i < (dgvTestHead.Rows.Count); i++)
{
if (dgvTestHead.Rows[i].Cells["Test_Head"].Value.ToString()
.StartsWith(e.KeyChar.ToString(),
true,
CultureInfo.InvariantCulture))
{
dgvTestHead.ClearSelection();
dgvTestHead.Rows[i].Cells[0].Selected = true;
dgvTestHead.FirstDisplayedScrollingRowIndex = i;
dgvTestHead.Refresh();
return; // stop looping
}
}
}
}
I think it happens because the CurrentRow
property of the DataGridView
doesn't change.
To set the CurrentRow
to the selected row (it is read-only), use:
dgvTestHead.CurrentCell = dgvTestHead.Rows[i].Cells[0];
this worked for me.
精彩评论