C#、WinForms - 使用 'ENTER' 按钮启动搜索过程

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

我正在寻找一种功能,使我能够在不单击 'Search' 按钮的情况下开始搜索我的 DGV。因此,我制作了一个搜索按钮,它在点击时启动搜索过程:

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

搜索值行索引:

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

现在我尝试打开一个新的 class 来激活 SearchButton 而无需点击它:

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

但是没用。我已经尝试了一些更改,但效果不佳。没有出现错误或异常,如果我使用 'ENTER' 按钮,什么也不会发生。

您需要将表单的 KeyPreview-属性 设置为 true。 然后,您可以像这样为表单上的所有控件实现 KeyDown-Event:

private void button1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) this.button1_Click(sender, e);
}

private void txt_search_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) this.button1_Click(sender, e);
}
...

您似乎是在搜索文本框中键入搜索查询。然后你可以直接hook textbox.KeyDown事件来得到你需要的结果。

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

有一个名为 AcceptButton 的表单 属性。按下回车键时调用。也许您可以将其设置为您的搜索按钮。

public Form1()
        {
            InitializeComponent();
            this.AcceptButton = button1;// button1 name of your button
        }