我使用此代码在DataGridView
中搜索以查找并选择一行(无过滤器)!但是,当DataGridView
在行中有重复值时,它不会获得下一行!每次点击Btn_find
(查找类似于Excel),我如何进入下一行?
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Find Next";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["ProductId"].Value == null)
{
continue;
}
if (row.Cells["ProductId"].Value.ToString().Trim() == textBox1.Text)
{
dataGridView1.CurrentCell = row.Cells["ProductId"];
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[row.Index].Index;
return;
}
}
}
答案 0 :(得分:1)
这个想法:
实现:
private int searchIndex = -1;
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Find Next";
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
searchIndex = (searchIndex + 1) % dataGridView1.Rows.Count;
DataGridViewRow row = dataGridView1.Rows[searchIndex];
if (row.Cells["Foo"].Value == null)
{
continue;
}
if (row.Cells["Foo"].Value.ToString().Trim() == textBox1.Text)
{
dataGridView1.CurrentCell = row.Cells["Foo"];
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[row.Index].Index;
return;
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
searchIndex = -1;
}
为什么要改变这些?
for (int i = 0; i < dataGridView1.Rows.Count; i++)
searchIndex = (searchIndex + 1) % dataGridView1.Rows.Count;
%
)会将我们返回到第一行。 private void textBox1_TextChanged(object sender, EventArgs e)
{
searchIndex = -1;
}