【问题标题】:searching using enter key on windows application? [closed]在 Windows 应用程序上使用 Enter 键进行搜索? [关闭]
【发布时间】:2012-11-30 09:53:25
【问题描述】:

我是 c# 的新手,我有一个 TextBox 和一个 gridview,当用户在 Textbox 中输入内容进行搜索时,单击搜索按钮时会成功填充 gridview。 但我担心的是搜索按钮使用 ENTER KEY 来搜索 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; 
     } 
 } 

我试过了,但没用

【问题讨论】:

  • 您的意思是您希望按 Enter 与单击“搜索”按钮具有相同的效果吗?还是您想从表单中删除“搜索”按钮?

标签: c# winforms


【解决方案1】:

您可以使用AcceptButton 属性。
在您的 Constructor 或 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;

【讨论】:

  • 他在textbox 中谈论enter key 而不是button
  • @Some1.Kill.The.DJ 即使它应该可以工作?
  • 设置AcceptButton意味着按下回车将与按下按钮本身具有相同的效果。
  • @Mr_Green 现在,它没有错。我的意思是说你的回答是正确的,尽管 Some1.Kill.The.Dj 的评论。
【解决方案2】:

在 KeyPress 事件上代替 TextChanged 事件。

首先将事件附加到文本框,无论是在设计器中还是在如下代码中:

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 事件调用相同的方法。

【讨论】:

  • @user187068,是的,在表单构造函数中执行此操作,或者您可以在设计器中附加事件
  • @user187068,不客气
【解决方案3】:
private void textBox3_KeyDown(object sender, KeyEventArgs e) {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多