如何通过在DataGridView中键入字符来关注单元格

时间:2017-07-07 11:02:26

标签: c# winforms datagridview keypress

我想专注于包含按下字符的单元格。

假设DataGridView包含两列,NameAddress。 现在在Name列中有很多记录(例如Nims, John, Kan, Rocks, Rita等等)。

现在,当我输入字符KAN时,该单元格将专注于Kan

我已经搜索了这个,但我发现只有下面的代码不能满足我的问题。

因为它是包含按下的字符作为单元格值的起始字符的聚焦单元格。

我尝试了什么:

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
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

1)您可以使用字符串进行搜索,而不是按字符搜索 2)使用Timer清除搜索字符串(一秒/两秒后)

示例C#代码

private void button1_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> dicNameAddress = new Dictionary<string, string>() { { "Nims", "India" }, { "john", "Japan" }, { "kan", "UK" }, { "kar", "USA" }, { "rita", "Germany" } };
        foreach (var nameAddress in dicNameAddress)
        {
            var rowIndex = dataGridView1.Rows.Add();
            dataGridView1.Rows[rowIndex].Cells[0].Value = nameAddress.Key;
            dataGridView1.Rows[rowIndex].Cells[1].Value = nameAddress.Value;
        }
    }

    static string searchText = string.Empty;

    private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetter(e.KeyChar))
        {

            searchText += e.KeyChar;
            timer1.Start();

            for (int i = 0; i < (dataGridView1.Rows.Count); i++)
            {
                if (dataGridView1.Rows[i].Cells[0].Value.ToString().StartsWith(searchText, true, CultureInfo.InvariantCulture))
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[i].Cells[0].Selected = true;
                    return;
                }
            }
        }
    }

    // Timer Interval 1000 (Clear the searchText text after one second for new search)
    private void timer1_Tick(object sender, EventArgs e)
    {
        searchText = string.Empty;
        timer1.Stop();     
    }