1

I'm building a simple winforms application in c#, which consists of few forms.

One of the forms in my application consists of a few different controls, which must meet certain conditions for the form to be valid, and an accept button.

What I want is for the button to be disabled until all the fields are valid, then enable it when the conditions are met, yet I couldn't find any method to do so...

I've came across OnValidating \ OnValidated but they're only invoke on acceptButton_Click. This of course requires me to enable the button by default, and assign the form's AcceptButton property to it.

I remember wpf have something for this sort of thing (filter?), but I'm not sure such thing exists for winforms.

iDaN5x
  • 616
  • 9
  • 12
  • You handle the `TextChanged` or similar events of each control that could have an effect on the button's state. – Cody Gray - on strike Feb 27 '16 at 13:56
  • you can override the controls and on validating event to trigger the form ( parent ) to validate ( where you code the button enabling or not ) this way you can make this behavior generic – Monah Feb 27 '16 at 14:08

1 Answers1

1

If you have a form with, for example, textBox1 and checkBox1 then you can handle the events and call the method, that updates the button:

    private void textBox1_TextChanged(object sender, EventArgs e) {
        updateButton();
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e) {
        updateButton();
    }

    private void updateButton() {
        button1.Enabled = textBox1.Text != string.Empty && checkBox1.Checked /* && other conditions */;
    }

You can also handle the Validating event:

    private void textBox1_Validating(object sender, CancelEventArgs e) {
        updateButton();
    }

    private void checkBox1_Validating(object sender, CancelEventArgs e) {
        updateButton();
    }

You will find some more ideas here:

Community
  • 1
  • 1
romanoza
  • 4,775
  • 3
  • 27
  • 44
  • This is an obvious solution. I wanted to know if there's a built-in solution, like then one in wpf. – iDaN5x Feb 27 '16 at 14:01
  • The right way to use the event-based validation is to check the condition in the `OnValidating` handler, and apply the controller update on then `OnValidated`. This solution is still using an explicit call to a an update function, and as I mentioned I already considered it... I guess an implicit solution doesn't exist after all... – iDaN5x Feb 27 '16 at 16:19
  • @iDaN5x That's right. That's why the handling of the `Validating` event is a relatively good way to modify the state of other controls based on the validation results. But the first method I wrote in my answer is the most common way to disabling the buttons on the form. Obvious? I'm not sure it's a drawback. – romanoza Feb 27 '16 at 17:15