Search datagridview on user keypress

前端 未结 5 1268
别跟我提以往
别跟我提以往 2021-02-09 05:09

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 hand

5条回答
  •  不思量自难忘°
    2021-02-09 05:23

    The edited answer in the original question doesn't support jumping to the next letter if there are multiple instances of names starting with the same letter. Here is an edited answer which support this feature:

    private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetter(e.KeyChar))
        {
            int index = 0;
            // This works only if dataGridView1's SelectionMode property is set to FullRowSelect
            if (dataGridView1.SelectedRows.Count > 0 )
            {
                index = dataGridView1.SelectedRows[0].Index + 1
            }
            for (int i = index; i < (dataGridView1.Rows.Count + index); i++)
            {
                if (dataGridView1.Rows[i % dataGridView1.Rows.Count].Cells["Name"].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
                {
                    foreach (var row in dataGridView1.Rows.Cast().Where(t => t.Selected))
                    {
                        row.Selected = false;
                    }
                    dataGridView1.Rows[i % dataGridView1.Rows.Count].Cells[0].Selected = true;
                    return; // stop looping
                }
            }
        }
    }
    

提交回复
热议问题