Search code examples
c#stringbuttontextboxisnullorempty

Textbox not checking if null or not


In my form application there is a textbox, and two buttons, I need to start a process, and in the textbox whenever it is empty I need the button below it to disable. I have tried the google'd help, i.e :

public void buttonenableordisable()
{
   if( String.IsNullOrEmpty(textBox1.Text))
   {
       button1.Enabled = false;
   }
   else
   {
       button1.Enabled = true;
    }
}

But it just disables the button, upon adding text to the textbox, the button doesn't enable, it stays greyed out. I have also tried,

if (string.IsNullOrWhiteSpace(textbox1.Text)) 
{
    button1.Enabled = false; // <<== No double-quotes around false
} 
else 
{
    // Don't forget to re-enable the button
    button1.Enabled = true;
}

But that doesn't work either. Any ideas ?

Thanks in advance.


Solution

  • You should bind to the TextChanged event of the textbox and call your method. It can also be simplified.

    As it is, you are only calling your method once when the form loads.

    public void buttonenableordisable()
    {
        button1.Enabled = !String.IsNullOrEmpty(textBox1.Text);
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        buttonenableordisable();
    }