Button enable and disable on text changed event

后端 未结 3 1288
囚心锁ツ
囚心锁ツ 2020-12-22 09:42

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?

相关标签:
3条回答
  • 2020-12-22 10:10

    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));
    
    0 讨论(0)
  • 2020-12-22 10:11

    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.

    0 讨论(0)
  • 2020-12-22 10:20

    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); 
    }
    
    0 讨论(0)
提交回复
热议问题