Monday, April 27, 2009

How to use the “ErrorProvider” control in a C# application

This is an example on how to use the “ErrorProvider” control in order to check whether there is something written in the textbox and validate a textbox .

Add a label with the name ‘label1’, a textbox with the name ‘txtText’ and a button with the name ‘btnValidate’ as given in the above form. Also add error provider control to the form with the name ‘errorProvider’. Rename the Form as ‘FormTextBoxValidator’.

Then add this method to the FormTextBoxValidator.cs to validate the textbox.

private bool textBoxValidate()
{

errorProvider.Clear();
if (txtText.Text.Trim() == "")
{
errorProvider.SetError(txtText, "Text should be non empty");
return false;
}
return true;
}

Then to the click event of the ‘ btnValidate’ add the following code.

private void btnValidate_Click(object sender, EventArgs e)
{
if (textBoxValidate())
{
MessageBox.Show("Content validated!");
}
}

When you run the application, and click the validate button without entering a text to the textbox, it will provide an error as follows.


If you enter some text to the textbox, it will validate the textbox.


Multisoft Extreme

Multisoft Extreme is a software developing company. We develop software for all business requirements. We are specialized in stock management systems, payroll systems and billing systems. For more information: multisoftextreme@gmail.com