C# 如果字符串为空或有空格,则禁用按钮?

C# 如果字符串为空或有空格,则禁用按钮?,c#,.net,winforms,button,user-interface,C#,.net,Winforms,Button,User Interface,我刚开始学C 这是我的密码: private void button1_Click(object sender, EventArgs e) { object Nappi1 = ("Nice button"); MessageBox.Show(Nappi1.ToString()); } 我得到了一个文本框,如果是空的或空白,它应该禁用按钮1 我已经让它在某种程度上工作了,但是它检查了按钮1上文本框的状态 private void button1_Click(object send

我刚开始学C

这是我的密码:

private void button1_Click(object sender, EventArgs e)
{
    object Nappi1 = ("Nice button");
    MessageBox.Show(Nappi1.ToString());
}
我得到了一个文本框,如果是空的或空白,它应该禁用
按钮1

我已经让它在某种程度上工作了,但是它检查了
按钮1上
文本框的状态

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])

  • 如何让它检查
    文本框的状态(程序启动后)
  • 如何让它检查(多个)
    空白
    ,并将其写入相同的
    if
    -语句
  • 请保持简单。

    你想要什么

    您最初有:

    if (textBox1 = "") {
    button1.enabled = false;
    }
    
    textbox
    是控件,您需要使用
    Text
    属性,该属性引用textbox控件内的字符串文本。在C#
    =
    中还有一个赋值,理想情况下,您希望使用
    =
    进行比较

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


    如果它只是一个
    字符串,则将if-else替换为该字符串:

    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;
        ...
    }
    

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

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

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

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

    private void textBox1\u TextChanged(对象发送者,事件参数e)
    {
    if(string.IsNullOrWhiteSpace(textBox1.Text))
    按钮1.启用=错误;
    其他的
    按钮1.启用=真;
    }

  • 默认情况下,禁用表单的InitializeComponent方法中的按钮

    button1.Enabled=false


  • 在textBox1 text changed事件中,右键单击此代码:

    button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
    
    IsNullOrWhiteSpace(“某些文本”)将检查文本是无文本还是仅为wightspaces
    如果这是真的,您将把button1.Enabled设置为false。

    String.IsNullOrWhiteSpace
    我知道您才刚刚开始,但我认为最好仔细查看对象和属性以及一些最常见的通知机制,如INotifyProperty,一旦你习惯了,它肯定会让你的生活变得更轻松!
    button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);