0

I am wondering how I can set a button to disable if there is no text inside a text box, but when there is re enable it? Would I put it into a text changed event?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208

3 Answers3

2

Something like that (WinForms):

private void myTextBox_TextChanged(object sender, EventArgs e) {
  myButton.Enabled = !String.IsNullOrEmpty(myTextBox.Text);       
}

EDIT: For initial form load you can use Load event:

private void myForm_Load(object sender, EventArgs e) {
  myButton.Enabled = !String.IsNullOrEmpty(myTextBox.Text); 
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • It works perfectly, although when the form is fist opened and no text has been entered it of course won't work, do you know how to fix that? –  Oct 12 '15 at 07:04
  • @Jeremy M: for initial load you can use `Load` event of the form – Dmitry Bychenko Oct 12 '15 at 07:06
  • Uhhhh I am terribly stupid :(. Thanks though, I will upvote your comment when possible. –  Oct 12 '15 at 07:10
0

Did you mean something like this?

if (!string.IsNullOrEmpty(textBox1.Text))
    button1.Enabled = true;
else
    button1.Enabled = false;

Don't forget that you can change the default property of that button.

Liren Yeo
  • 3,215
  • 2
  • 20
  • 41
0

You can do it in a more structured way using data binding and the little helper from here Exchange UserControls on a Form with data-binding

static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
{
    var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
    binding.Format += (sender, e) => e.Value = expression(e.Value);
    target.DataBindings.Add(binding);
}

Note that this is reusable piece of code that you can use in many scenarios. For your particular case, all you need is (after copying the code above) to put the following line in your form load event:

Bind(button1, "Enabled", textBox1, "Text", value => !string.IsNullOrEmpty((string)value));
Community
  • 1
  • 1
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343