在Windows应用程序上使用enter键搜索?

时间:2012-11-30 09:53:25

标签: c# winforms

我是c#的新手,我有一个TextBox和一个gridview,当用户在Textbox中输入内容进行搜索时,gridview会在点击搜索时成功填写按钮。 但我关注的是搜索按钮使用ENTER KEY TO在gridview中搜索数据。

private void textBox3_TextChanged(object sender, KeyPressEventArgs e1, EventArgs e) 
{
    if (e1.KeyCode == Keys.Enter) 
    { 
       string sql = "[DocEntry],[JobCardNo],[ITEMNAME],[OD] ,[PlanQty],
                      [FinalInspectionRemarks] ,[OrderDate] ,[Division]
                          WHERE JobCardNo ='" + textBox3.Text.ToString() + "'";  
       SqlDataAdapter da = new SqlDataAdapter(sql, objConn1); DataSet ds = new DataSet(); 
       objConn1.Open(); 
       da.Fill(ds, "ProductionInventoryReport"); 
       dataGridView1.DataSource = ds; //dataGridView1.DataBind();  
       dataGridView1.DataMember = "ProductionInventoryReport"; 
       objConn1.Close(); e1.Handled = true; 
     } 
 } 

我试过这个但没有工作

3 个答案:

答案 0 :(得分:1)

您可以使用AcceptButton属性。
构造函数 Form_Load 事件中尝试以下代码。

this.AcceptButton =  //give your search Button name here


如果您想删除搜索按钮,那么您可以使用以下代码:(粗略代码)

Button btnSearch = new Button();  //Create a New Button
btnSearch.Visible = false;         //Optional
btnSearch.Click += new EventHandler(/*Your Method name for Search*/);
this.AcceptButton = btnSearch;

答案 1 :(得分:0)

而不是TextChanged事件在KeyPress事件上执行。

首先将事件附加到文本框中,可以是设计器,也可以是代码:

textBox3.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox3_KeyPress);

然后

 private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) // enter key pressed
            { 
             //searchMethod(); 
            }
        }

如果将搜索代码提取到单独的方法然后针对搜索按钮和KeyPress事件调用相同的方法,则会更好。

答案 2 :(得分:0)

private void textBox3_KeyDown(object sender, KeyEventArgs e) {

    if (e.KeyCode == Keys.Enter)
    {
        //Your searchMethod();
    }
}