Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Disable button if string empty or has whitespace?

I just started learning C#.

Here's my code:

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

I got a textbox, that should disable the button1 if empty or whitespace.

I already got it working in some level, but it checks the state of the textbox on button1_Click.

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());
    }
}

Fictional example:

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

  1. How could I make it check the state of the textbox onLoad (as soon as the program starts)?
  2. How could I make it check if (multiple) whitespace, and can I write it to the same if -statement?

Please keep it simple.

like image 828
Claudio Avatar asked Dec 06 '22 03:12

Claudio


2 Answers

To answer exactly the question title, Shorter, clearer:

button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
like image 97
Askolein Avatar answered Dec 10 '22 12:12

Askolein


Replace your if-else with this, if it is only a string:

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

or use textBox1.Text if it is really a Textbox use this:

if (string.IsNullOrWhiteSpace(textBox1.Text)) {
    button1.enabled = false;
}
else {
    button1.enabled = true;
    ...
}
like image 32
Jon P Avatar answered Dec 10 '22 13:12

Jon P