4

这就是我用来允许输入按钮开始搜索的方法。它可以工作,但会导致系统发出哔哔声。我不知道为什么。

    private void searchbox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            searchbutton.PerformClick();
        }
        else
        {
            //Run.
        }

    }

一旦我按下回车而不是代码中的其他行,它就会发生。对我缺少什么的想法?

这是searchbutton_Click:

    private void searchbutton_Click(object sender, EventArgs e)
    {
        var searchvar = searchbox.Text;
        SqlParameter var1 = new SqlParameter(@"var1", SqlDbType.Text);
        var1.Value = "%" + searchvar + "%";
        var conn = new SqlConnection("Data Source=TX-MANAGER;Initial Catalog=Contacts;Integrated Security=True");
        var comm = new SqlCommand(@"SELECT [Name ID], First, Last, Address, City, State, ZIP FROM contacts WHERE (First LIKE @var1) OR (Last LIKE @var1)", conn);
        if (checkBox1.Checked == true)
        {
            comm.CommandText += "ORDER BY ZIP";
        }
        else
        {
            //Run.
        }
        try
        {
            comm.Parameters.Add(var1);
            conn.Open();
            comm.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(comm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            conn.Close();
        }
        catch (Exception e1)
        {
            display_box.Text = e1.ToString();
            tabControl1.Focus();
        }
        finally
        {
            int rowcount = dataGridView1.RowCount - 1;
            count.Text = rowcount.ToString();
            tabControl1.SelectedTab = tabPage2;
        }

    }
4

2 回答 2

1

您可以尝试e.Handled = true;KeyPressed您的TextBox.

通常,如果您Form没有AcceptButton设置其属性,则在TextBox. 哔声表示没有为您的Form.

于 2012-06-19T14:56:35.270 回答
1

添加以下事件处理程序(除了KeyUp):

private void searchbox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '\r')
        e.Handled = true;
}

也就是说,订阅KeyPress事件并且当Enter被按下时,设置e.Handledtrue。我刚刚在我的机器上测试了它并且它有效;它消除了哔哔声。

于 2012-06-19T15:04:02.160 回答