【问题标题】:Clicking button validates text box in C# but doesn't trigger the button event单击按钮验证 C# 中的文本框,但不会触发按钮事件
【发布时间】:2016-05-25 22:06:48
【问题描述】:

我有 C# 中的 UI 表单,带有一堆组合框和一个文本框。我有与文本框关联的验证和验证事件,以确保用户选择有效输入。我在表单中还有一个“查看结果”和“导出结果”按钮。当我单击两个按钮中的任何一个时,它肯定会验证文本框输入,但不会执行按钮应该执行的操作。我必须再次单击该按钮才能触发该按钮应该执行的操作。

我应该怎么做才能使按钮单击事件既进行验证又执行它打算执行的操作?

这是我的代码的摘录

private void NameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (!isValidName())
     {
         e.Cancel = true;
         NameTextBox.Select(0,NameTextBox.Length);
         InvalidPMLabel.Visible = true;
         InvalidPMLabel.Text = "Invalid Name";
         ExportButton.Enabled = false;
         ViewResultsButton.Enabled = false;
         GroupTextBox.Clear();
    }
 }  



private void NameTextBox_Validated(object sender, EventArgs e)
{
    string combination = null;
    int index = -1;
    sql = "select .......";
    dSet = get_data(sql);
    MaxRows = dSet.Tables[0].Rows.Count;
    if (MaxRows != 0)  
    {
        dSet.Clear();
        ...
        ...
    }
    else
    {
        ...
        ...
        ...
    }
    GroupTextBox.Text = dSet.Tables[0].Rows[index]["group"].ToString(); 
}

private void ViewResultsButton_Click(object sender, EventArgs e)
{
    view_marks();
    view_grade();
}

【问题讨论】:

    标签: c# textbox validating


    【解决方案1】:

    我认为当您的代码执行e.Cancel = true; 行时,它会阻止按钮事件继续。试试去掉这部分,看看验证后是否执行了事件。

    【讨论】:

      【解决方案2】:

      所以我注意到您正在使用事件来进行验证。 您有 2 个选项。您可以在 onclick 事件中调用这些验证事件,或者使用一种方法进行验证并调用该方法。我是方法路线的粉丝,所以我将展示这一点

      private bool Validated()
      {
          bool check;
          //do all your code and set a value for check
      
          return check;
      
      }
      
      
      private void ViewResultsButton_Click(object sender, EventArgs e)
      {
         if(Validated() == true)
          {
      
          view_marks();
          view_grade();
          }
      }
      

      另一条路线对事件做同样的事情,但我以前没有这样做过。

      【讨论】:

        猜你喜欢
        • 2012-01-19
        • 2016-04-25
        • 2012-09-12
        • 2019-06-22
        • 2017-06-06
        • 1970-01-01
        • 2019-07-05
        • 2020-02-20
        • 1970-01-01
        相关资源
        最近更新 更多