Alex Alex - 1 month ago 5
C# Question

How to Validate Form

I have a windows form for a desktop app that has 7 fields,

how can I have the submit button disabled until the form validates?

I know I can validate the form when the user clicks the button, but if i have the button disabled what is the best way to call my validation method?

Using C# express 2008.

Answer

You can always call the validation method from the change event of all 7 controls. If you have bound the controls to some datasource the datasource shuld have an OnUpdated event.

private void TextBox1_Changed(object sender, EventArgs e)
{
 Validate();
}

private void ComboBox2_Changed(object sender, EventArgs e)
{
 Validate();
}

private void Validate()
{
 if(ValidationOk())
 {
  Button1.Enabled = true;
 }
 else
 {
  Button1.Enabled = false;
 }

}

Or maybe:

private void Validate()
{
 Button1.Enabled = ValidationOk();
}
Comments