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



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

假设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(您可以使用字符串搜索,而不是按字符搜索 2(使用计时器清除搜索字符串(一/两秒后(

示例 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();     
}

最新更新