How can I create an excel search in a DataGridView?

I used this code to search in DataGridView

to find and select a row (no filter)! But, when DataGridView

has duplicate values ​​in rows, it will not get the next row! How to move to the next line with every button click Btn_find

(Find Similar in 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;
        }
    }
} 

      

+3


source to share


1 answer


Idea:

  • Add a private field to the class as an index to remember which row you found.
  • Reset this index if the search text has changed. (Not necessary)
  • Loop over all lines, starting with the line following the last successful search. If no search results are found, start over.

Implementation:

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

      




Why are these changes?

  • for (int i = 0; i < dataGridView1.Rows.Count; i++)

    • Repeat all lines.
  • searchIndex = (searchIndex + 1) % dataGridView1.Rows.Count;

    • Start at line [searchIndex + 1]. When we get to the last line, mod ( %

      ) returns us to the first line.
  • private void textBox1_TextChanged(object sender, EventArgs e) { searchIndex = -1; }

    • Start at the top of the list as new search criteria are entered. It's not obligatory.
+1


source







All Articles