Error Provider Control
This control provides a user interface that indicates to user that a control on a form has error associated with it. In other had it works as validation upon the controls to handle the error causes by inputting wrong by user.Drag this control as shown in below picture -
Adding error provider control on textbox for blank not allow-
Write this code on textbox validating event- Output will shown in below picture if user leave name blank.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
ValidateName();
}
private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError(textBox1, "Please enter your Name");
bStatus = false;
}
else
errorProvider1.SetError(textBox1, "");
return bStatus;
} |
Validating for age. For validating age i have covered three conditions for validate
1-If user leave this blank.
2-If entered age is less than 18.
3-If user input character value in place of numeric.
Write this code on Textbox2 validating Event-
private void textBox2_Validating(object sender, CancelEventArgs e)
{
ValidateAge();
}
private bool ValidateAge()
{
bool bStatus = true;
if (textBox2.Text == "")
{
errorProvider1.SetError(textBox2, "Please enter your Age");
bStatus = false;
}
else
{
errorProvider1.SetError(textBox2, "");
try
{
int temp = int.Parse(textBox2.Text);
errorProvider1.SetError(textBox2, "");
if (temp < 18)
{
errorProvider1.SetError(textBox2, "You must be atleast 18 years old to setup a test");
bStatus = false;
}
else
{
errorProvider1.SetError(textBox2, "");
}
}
catch
{
errorProvider1.SetError(textBox2, "Please enter your age as a number");
bStatus = false;
}
}
return bStatus;
} |
Output of this error provider is shown below-
Using error provider control on DatetimePicker Control
If user select weekend day for test then he will get error message- Like shown in below picture
private void dateTimePicker1_Validating(object sender, CancelEventArgs e)
{
ValidateTestDate();
}
private bool ValidateTestDate()
{
bool bStatus = true;
if ((dateTimePicker1.Value.DayOfWeek ==DayOfWeek.Sunday) ||(dateTimePicker1.Value.DayOfWeek
==DayOfWeek.Saturday))
{
errorProvider1.SetError (dateTimePicker1, "Appointment cannot be scheduled in
the weekend. Please select a weekday");
bStatus = false;
}
else
errorProvider1.SetError (dateTimePicker1, "");
return bStatus;
} |
No comments:
Post a Comment