Search code examples
c#.netwinformsdatagridviewkeypress

Search datagridview on user keypress


I'm trying to select the first row where the cell value starts with the same keychar the user pressed. That's the part that is giving me trouble.

Here's how I'm handling the event (updated with working solution):

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsLetter(e.KeyChar))
    {
        for (int i = 0; i < (dataGridView1.Rows.Count); i++)
        {
            if (dataGridView1.Rows[i].Cells["Name"].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
            {
                dataGridView1.Rows[i].Cells[0].Selected = true;
                return; // stop looping
            }
        }
    }
}

I'm sure it's something simple that I'm overlooking, but for the life of me can't figure out what it is.

EDIT

Updated the code with solution applied


Solution

  • Might be a case issue, is the Value in Cells["Name"] start with a capital letter? Try using ToUpper or ToLower on both; or you could try StartsWith(e.KeyChar, true) to ignoreCase. If you are trying to select the row, you'll want to do dataGridView1.Rows[i].Selected = true