Monday, December 29, 2008

C# windows validation by ErrorProvider Control

C# Windows Validation by ErrorProvider

In ASP.Net 2.0 we use different Validation controls from Toolbox for validations (Just Drag & Drop, No need of writing code in C#). But in Case of C# windows application this feature is not available so we use Error Provider control to do any type of validation.

For example:-

If we take a Employee data…

  1. Name (Text)
  2. Age (Integer)
  3. Salary (Double)

Form looks like

In ADD button click you need to write the following code.

private void ADD_Click(object sender, EventArgs e)

{

if (is_validate())

{

errorProvider1.Clear();

// Write Coding to add into database

MessageBox.Show("Data Successfully Added");

}

}

private bool is_validate()

{

bool no_error = true;

if (txtname.Text == string.Empty)

{

errorProvider1.SetError(txtname, "Text Missing");

no_error = false;

}

else

{

// Clear all Error Messages

try

{

int i = Convert.ToInt32(txtage.Text);

}

catch

{

errorProvider1.Clear(); // Clear all Error Messages

errorProvider1.SetError(txtage, "Enter Valid Age");

return false;

}

try

{

double j = Convert.ToDouble(txtsalary.Text);

}

catch

{

errorProvider1.Clear(); // Clear all Error Messages

errorProvider1.SetError(txtsalary, "Enter Valid Salary");

return false;

}

}

return no_error;

}

Here one Error Provider Control can be used for multiple fields.

That’s it. It’s all done. Its Very Simple isn’t it??

No comments: