【问题标题】:How can i check if both textBoxes are with text inside and then to enable another button?如何检查两个文本框是否都带有文本,然后启用另一个按钮?
【发布时间】:2014-11-11 06:18:25
【问题描述】:

在我做的构造函数中:

public Form1()
        {
            InitializeComponent();

            if ((txtHost.Text == "") || txtUploadFile.Text == "")
            {
                btnUpload.Enabled = false;
            }
        }

但我想要做的是,如果用户在两个文本框中输入文本或检查两个文本框内是否有文本,则启用 btnUpload true。

也许我需要一个活动或什么?但是我想检查只有当两个复选框 txtHost 和 txtUploadFile 里面有文本时才启用真正的按钮 btnUpload。

【问题讨论】:

  • 或者也许这样做 btnUpload 将被启用,但如果用户在两个文本框为空或其中一个为空的情况下单击它,则会向用户显示红色错误消息,文本框可以'不要为空,例如在注册网站时填写表格。
  • 使用 TextChanged 事件。

标签: c# .net winforms


【解决方案1】:

试试这个

public Form1()
{
    InitializeComponent();

    txtHost.TextChanged += textBox_TextChanged;
    txtUploadFile.TextChanged += textBox_TextChanged;

    textBox_TextChanged(null, null);
}

private void textBox_TextChanged(Object sender, EventArgs e)
{
    btnUpload.Enabled = txtHost.TextLength > 0 && txtUploadFile.TextLength > 0;
}

【讨论】:

    【解决方案2】:

    连接以下事件。这是代码posted by Phill W. on MSDN的摘录。

       textBox1.TextChanged += anyTextBox_TextChanged; 
    
       textBox6.TextChanged += anyTextBox_TextChanged; 
    
    
    private void anyTextBox_TextChanged( object sender, TextChangedEventArgs e )
    {
      // ... ask the button to check its own state. 
      button1_CheckState(); 
    }
    
    
    private void button1_CheckState() 
    {
     // Assume all is well to start with 
      bool state = true ; 
    
     foreach ( TextBox textBox in textBoxes_ )
      if ( "".Equals( textBox.Text ) ) 
      {
         // If it's not, disable the button. 
         state = false ; 
         break ;
      }
    
     button1.Enabled = state ; 
    }
    

    【讨论】:

      【解决方案3】:

      编写一个事件处理程序并将其分配给两个文本框上的 TextChanged 事件。事件代码为 btnUpload.Enabled = txtHost.Text.Length > 0 && txtUploadFile.Text.Lenght > 0。

      【讨论】:

        【解决方案4】:

        使用 != 运算符。 前任。如果(文本!=“”) 然后将 Btnupload 设置为 true。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-27
          • 2019-12-16
          • 2023-03-14
          相关资源
          最近更新 更多