【问题标题】:C# - Disable button if string empty or has whitespace?C# - 如果字符串为空或有空格,则禁用按钮?
【发布时间】:2014-04-04 07:40:37
【问题描述】:

我刚开始学习 C#。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    object Nappi1 = ("Nice button");
    MessageBox.Show(Nappi1.ToString());
}

我有一个文本框,如果为空或空格,它应该禁用 button1

我已经让它在某种程度上工作,但它会检查 button1_Click 上的 textbox 的状态。

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1 = "") 
    {
        button1.enabled = false;
    }
    else 
    {
        button1.enabled = true;
        object Nappi1 = ("Nice button");
        MessageBox.Show(Nappi1.ToString());
    }
}

虚构的例子:

 if (textBox1 = "" or textBox1 = whitespace[s])

  1. 如何让它检查textbox onLoad 的状态(程序一启动)?
  2. 如何让它检查(多个)whitespace,我可以将其写入相同的if -statement 吗?

请保持简单。

【问题讨论】:

  • String.IsNullOrWhiteSpace
  • 我知道你才刚刚开始,但我认为最好仔细看看对象和属性以及一些最常见的通知机制,如 INotifyProperty,它肯定会让一旦你习惯了,你的生活会更轻松!

标签: c# .net winforms button user-interface


【解决方案1】:

在 textBox1 文本更改事件中,右键此代码:

button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);

string.IsNullOrWhiteSpace("some text") 将检查文本是否为空或只是一个 wightspaces 如果这是真的,你会将 button1.Enabled 设置为 false。

【讨论】:

    【解决方案2】:

    要准确回答问题标题,更短,更清晰:

    button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
    

    【讨论】:

      【解决方案3】:

      这可以通过将事件处理程序挂钩到文本框文本更改事件来完成。 步骤:

      1. 为文本框附加一个事件处理程序(在文本更改时) 在文本更改事件处理程序中启用/禁用按钮。

        private void textBox1_TextChanged(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBox1.Text)) button1.Enabled = false; else button1.Enabled = true; }

      2. 在表单的InitializeComponent方法中默认禁用按钮

        button1.Enabled = false;

      【讨论】:

        【解决方案4】:

        你想要String.IsNullOrWhiteSpace:

        if (String.IsNullOrWhiteSpace(textBox1.Text)) {
            button1.enabled = false;
        }
        

        你原来有:

        if (textBox1 = "") {
        button1.enabled = false;
        }
        

        textbox 是控件,您需要使用Text 属性,它引用文本框控件内的字符串文字。同样在 C# 中,= 是一个赋值,理想情况下你会希望 == 用于比较。

        如果您不使用.NET 4.NET 4.5,您可以使用:

        String.IsNullOrEmpty

        【讨论】:

          【解决方案5】:

          用这个替换你的 if-else,如果它只是一个 string:

          if (string.IsNullOrWhiteSpace(textBox1)) {
              button1.enabled = false;
          }
          else {
              button1.enabled = true;
              ...
          }
          

          或者使用textBox1.Text,如果它真的是Textbox,使用这个:

          if (string.IsNullOrWhiteSpace(textBox1.Text)) {
              button1.enabled = false;
          }
          else {
              button1.enabled = true;
              ...
          }
          

          【讨论】:

            猜你喜欢
            • 2018-11-28
            • 2020-09-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-05
            • 2020-06-03
            相关资源
            最近更新 更多