Search code examples
c#winformssearchbuttonenter

C#, WinForms - Starting Search Process with 'ENTER' Button


I am searching for a function that gives me the ability to start searching through my DGV without clicking on my 'Search' Button. Therefor I made a search button which starts the search process on click:

private int SearchValueRowIndex()
        {
            string searchValue = textBox1.Text;

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.Value != null && cell.Value.ToString() == searchValue)
                    {
                        return cell.RowIndex;
                    }
                }
            }
            // Not found
            return -1;
        }

The SearchValueRowIndex :

    private int SearchValueRowIndex()
    {
        string searchValue = textBox1.Text;

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.Value != null && cell.Value.ToString() == searchValue)
                {
                    return cell.RowIndex;
                }
            }
        }

Now I tried to open a new class for the activation of the SearchButton without a need to click on it:

 private void button1_KeyPress(object sender, KeyEventArgs e)
    {
        if (e.KeyValue.ToString() == Keys.Enter.ToString())
        {
            button1.PerformClick();
        }
    }

But it doesn't work. I already tried a few changes, which didn't work out as well. There is no Error or Exception appearing, just nothing happens if I use the 'ENTER' Button.


Solution

  • It seems like you are typing search query in a search textbox. Then you can directly hook textbox.KeyDown event to get your required result.

        private void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //Perform search
            }
        }