C# windows validation by ErrorProvider Control
May 16, 2008 by Ganesh Mohan
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…
- Name (Text)
- Age (Integer)
- 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??
hello ganesh,
i need coding for name,age,text,salary and all the details must be added into the list view when i click list view.
can u help me.
Hi Rekha,
This coding is only for validation (User Interface Part).
How do you want the code for name, age & salary??
You want the details to be added in Database or you want the added details to be displayed from the database in the list?? and you want in windows or web ?? since errorprovider is only for windows.
Thanks & Regards
Ganesh Mohan
hello ganesh,
thx for the reply.I am not using any database here.
its from windows.
i have Name,Age,Text,Salary text field.
and have add button and when i click add button
all details must be added into ListView.
and all the text feilds are mandatory.
hello ganesh,
i worked on the code u gave,
its really good.but how do i write code without using error provider.because i require it to show the message?
is their is any ways to do.can u guide me.
Hi Rekha,
You can insert message box instead of error provider(very simple)… and is your list view is a Datagrid?? you better come online in google/yahoo so that I can help you there… my gmail ID is ganeshmohan99 and yahoo ID is ganes_mohan99.
Thanks & Regards
Ganesh Mohan
Once again thank you ganesh.
i have added to my gmail.