floormind
floormind

Reputation: 2028

How do I enable button while there is a string in my textbox?

I have a textbox and a button in form2. When an item is clicked in form1, form2 appears. I would like to keep the button in form2 disabled while the textbox is empty, but when user starts typing, I'd like to enable the button.

I have tried using an if in my constructor after the initialisecomponent() like so, but it does not work:

if(textbox1.text != "")
{
   btnOne.Enabled = true;
}

I have also tried calling a method called checkText() after the initialise component which uses a do-while loop to check like:

do{
    btnOne.Enabled = true
  }
 while(textbox1.text != "");

Can anyone help?

Upvotes: 5

Views: 7506

Answers (3)

musefan
musefan

Reputation: 48465

You need to use an event. Check out the TextChanged event for the TextBox control.

Basically you will want something like this:

private void textbox1_TextChanged(object sender, EventArgs e)
{
    btnOne.Enabled = !string.IsNullOrEmpty(textbox1.Text);
}

If you are using Visual Studio you can do the following to add the event code.

  • Open designer view
  • Select the TextBox control
  • View the "Events" window
  • Find the "TextChanged" event
  • Double-click the value space, and the code will be added automatically for you to work with

Note: This approach will require the user to "lose focus" on the TextBox control before the event fires. If you want an as-you-type solution then check out the KeyUp event instead

@Asif has made a good point regarding checking for whitespace characters too. This is your call on what is valid, but if you do not want to allow whitespace value to be used then you can use the IsNullOrWhiteSpace method instead - however, this requires you to be using .Net Framework 4.0 or higher

Upvotes: 9

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

In case you don't allow white spaces as a valid input then you should use string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty.

textbox1.TextChanged += (sender, e)
{
    btnOne.Enabled = !string.IsNullOrWhiteSpace(textbox1.Text);
};

Upvotes: 0

Nipun Ambastha
Nipun Ambastha

Reputation: 2573

Use Textbox changed event in windows form

Upvotes: 0

Related Questions