C# Windows Application provides an ErrorProvider control, which is similar to the ValidationSummary control in Asp.Net, this control consolidates all the error messages in the form and alerts the user on the Form errors.
In this post we shall see on how to use the ErrorProvider control to validate a ComboBox in a C# Windows Form.
1. Create a new / open an existing C# Windows application
2. Open and existing / Add a new Windows Form to the Project
3. Add the required controls to the Form, let us add a ComboBox for Gender, In the Items (collection) property of the ComboBox, add options –Select--, Male and Female.
4. Open the ToolBar, Drag an ErrorProvider control into the form.
5. The ErrorProvider control can be found in the Components section.
5. The control gets added to the control tray at the bottom of the Form in the Design View.
6. Provide a name to the ErrorProvider, let us give is as errSummary
7. Use
the Constructor to set the Initial value of the ComboBox controls, also reset
the error after initializing the values.
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 0;
errSummaryBMR.SetError(comboBox1, "");
errSummaryBMR.SetError(comboBox2, "");
8. Now in the SelectedIndexChanged event of the ComboBox, we shall add code to
validate the ComboBox as follows.
boolFormValid = true;
//
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
boolFormValid = true;
//
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ValidateGender();
}
//
//
private
void ValidateGender()
{
// Check
if a Valid Option is Selected
if
(comboBox2.SelectedItem.ToString() == "--Select--")
{
errSummaryBMR.SetError(comboBox2, "Please
select your Gender.");
boolFormValid = false;
return;
}
else
{
errSummaryBMR.SetError(comboBox2, "");
}
}
9. Once we set the control and Error Message to the ErrorProvider control, an Alert icon is displayed to the user and the error message is displayed as a ToolTip.
10. The boolFormValid is a Form level bool variable, which is set to false, when any of the validations fail, while submitting the form, make sure that this is true, else alert the user to correct the validation errors.
private void cmdSubmit_Click(object sender, EventArgs e)
9. Once we set the control and Error Message to the ErrorProvider control, an Alert icon is displayed to the user and the error message is displayed as a ToolTip.
10. The boolFormValid is a Form level bool variable, which is set to false, when any of the validations fail, while submitting the form, make sure that this is true, else alert the user to correct the validation errors.
private void cmdSubmit_Click(object sender, EventArgs e)
{
boolFormValid = true;
ValidateGender();
//
if
(!boolFormValid)
{
MessageBox.Show("Please correct the Validation Error.");
return;
}}
No comments:
Post a Comment