How do I actually find something like this?

I want to create a search in a form like EXCEL, find and put (string) in the listview this is my form: enter image description here

and my code:

private int searchIndex = -1;
    private void button1_Click(object sender, EventArgs e)
    {
        button1.Text = "Find Next";
        try
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                searchIndex = (searchIndex + 1) % dataGridView1.Rows.Count;
                DataGridViewRow row = dataGridView1.Rows[searchIndex];
                if (row.Cells["Product"].Value == null)
                {
                    continue;
                }

                if (row.Cells["Product"].Value.ToString().Trim().StartsWith(textBox1.Text) || row.Cells["Product"].Value.ToString().Trim().Contains(textBox1.Text))
                {
                    ListViewItem lvi = new ListViewItem(row.Cells["Product"].Value.ToString()); 
                    lvi.SubItems.Add(row.Cells["Product"].Value.ToString());
                    listView1.Items.Add(lvi);
                    dataGridView1.CurrentCell = row.Cells["Product"];
                    dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[row.Index].Index;
                    row = dataGridView1.Rows[i];
                    return;
                }
            }
        }
        catch { }
    }

      

and in textbox1_textchanged:

searchIndex = -1;
        button1.Text = "Find";
        listView1.Clear();

      

I want when the search ends send a message ... thanks

0


source to share


1 answer


Playing a function Find All

, filling yours ListView

will be very similar to functionality Find Next

. Here's an example if it were a separate button from Find Next

:

public Form1()
{
  InitializeComponent();
  listView1.View = View.Details;
  listView1.Columns.Add("Column");
  listView1.Columns.Add("Row");
  listView1.Columns.Add("Value");
}

private void button2_Click(object sender, EventArgs e)
{
  button2.Text = "Find All";
  int tempIndex = -1;
  listView1.Items.Clear();

  for (int i = 0; i < dataGridView1.Rows.Count; i++)
  {
    tempIndex = (tempIndex + 1) % dataGridView1.Rows.Count;
    DataGridViewRow row = dataGridView1.Rows[tempIndex];

    if (row.Cells["Foo"].Value == null)
    {
      continue;
    }

    if (row.Cells["Foo"].Value.ToString().Trim().StartsWith(textBox1.Text) || row.Cells["Foo"].Value.ToString().Trim().Contains(textBox1.Text))
    {
      DataGridViewCell cell = row.Cells["Foo"];
      ListViewItem lvRow = new ListViewItem(new string[] { cell.ColumnIndex.ToString(), cell.RowIndex.ToString(), cell.Value.ToString() });
      listView1.Items.Add(lvRow);
    }
  }

  MessageBox.Show("Search ended."); // Or whatever message you intend to send.
}

      



Example screenshot.

+1


source







All Articles