如何在c#中按键时逐个搜索网格中的单元格
本文关键字:搜索网 搜索 网格 单元格 | 更新日期: 2023-09-27 18:23:37
如何在c#
中按键时逐个搜索网格中的单元格?
我试了几次key press event
,但都没用。
有一个例外。
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[0].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
{
list.Add(dataGridView1.Rows[i].Cells[0].Value.ToString());
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == list[i].ToString())
{
dataGridView1.Rows[i].Cells[0].Selected = true;
}
//dataGridView1.Rows[i].Cells[0].Selected = true;
/*if (dataGridView1.Rows[i].Cells[0].Selected == true)
{
dataGridView1.Rows[i].Cells[0].Selected = false;
} */
// stop looping
}
}
}
}
这一行没有意义,也可能导致IndexOutOfBoundExceptionArgumentOutOfRangeException
,因为不是每一行都可以添加到列表中,所以i
可能大于列表计数。
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == list[i].ToString())
删除列表,它应该工作:
private int lastIndex;
private char lastKey;
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[0].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
{
if (lastKey == e.KeyChar && lastIndex < i)
{
continue;
}
lastKey = e.KeyChar;
lastIndex = i;
dataGridView1.Rows[i].Cells[0].Selected = true;
return;
}
}
}
}
终于找到了答案。它会这样解决的。
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[0].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
{
if (lastKey == ''0')
{
lastKey = e.KeyChar;
if (lastKey == e.KeyChar && lastIndex < i)
{
int last = lastIndex;
lastIndex = i;
lastKey = e.KeyChar;
this.clearGrid(last);
dataGridView1.Rows[i].Cells[0].Selected = true;
return;
}
else
{
continue;
}
}
else
{
if (lastKey != e.KeyChar)
{
int last = lastIndex;
lastIndex = i;
lastKey = e.KeyChar;
this.clearGrid(last);
dataGridView1.Rows[i].Cells[0].Selected = true;
return;
}
else
{
// int last = lastIndex;
if (lastKey == e.KeyChar && lastIndex < i)
{
int last = lastIndex;
lastIndex = i;
lastKey = e.KeyChar;
this.clearGrid(last);
dataGridView1.Rows[i].Cells[0].Selected = true;
return;
}
else
{
continue;
}
}
}
}
else
{
continue;
}
}
}
}
private void clearGrid(int l)
{
dataGridView1.Rows[l].Cells[0].Selected = false;
}