hi i am working on my college project on Visual Studio 2010 C#. I have a WinForms application which has 8 textboxes. Whenever the user leaves the textbox empty, the error icon should pop up and a label besides it should be made visible displaying the error message.
When I execute the code below only the first two error providers work. The rest do not show up.
Could anyone help me?
private void textBox1_Leave(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text))
{
errorProvider1.SetError(textBox1,"REQUIRED FIELD");
label12.Text = "REQUIRED FIELD";
}
else
{
errorProvider1.Dispose();
}
}
private void textBox2_Leave(object sender, EventArgs e)
{
monthCalendar1.Visible = false;
if (String.IsNullOrEmpty(textBox2.Text))
{
errorProvider2.SetError(textBox2,"REQUIRED FIELD");
label13.Text = "REQUIRED FIELD";
}
else
{
errorProvider2.Dispose();
}
}
private void textBox3_Leave(object sender, EventArgs e)
{
if (textBox3.Text=="")
{
errorProvider3.SetError(textBox3, "REQUIRED FIELD");
label14.Text = "REQUIRED FIELD";
}
else
{
errorProvider3.Dispose();
}
}
private void textBox4_Leave(object sender, EventArgs e)
{
monthCalendar1.Visible = false;
if (String.IsNullOrEmpty(textBox4.Text))
{
errorProvider4.SetError(textBox4, "REQUIRED FIELD");
label15.Text = "REQUIRED FIELD";
}
else
{
errorProvider4.SetError(textBox4, "");
}
}
private void textBox5_Leave(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox5.Text))
{
errorProvider5.SetError(textBox5, "REQUIRED FIELD");
label16.Text = "REQUIRED FIELD";
}
else
{
errorProvider5.SetError(textBox5, "");
}
}
private void textBox6_Leave(object sender, EventArgs e)
{
monthCalendar2.Visible = false;
if (String.IsNullOrEmpty(textBox6.Text))
{
errorProvider6.SetError(textBox6, "REQUIRED FIELD");
label17.Text = "REQUIRED FIELD";
}
else
{
errorProvider6.SetError(textBox6, "");
}
}
You dispose your error provider whenever someone inputs text in the text box. Disposing an object frees all resources and prevents further usage.
Use the
Clear()
method of the error provider instead. This will clear all errors. If you want to clear only a single error, set an empty text.And - usually - you do need only one error provider per Form.
EDIT: provided fully working example
This is reduced to handling the error provider. Whenever the cursor leaves a text field, this field is check for contents. If empty, the error is shown. The user needs to return to the field, enter dta and leave again to clear the error. This is basically what you defined as requirement in your example. I left out switching the label text, but that does not seem to be the problem.
To check out, create a new WinForm-Application and replace the class Form1 with this code. For brevity, i included the
InitialiseComponent()
code in the constructor, so probably VS will not show the form (at least VS2010 doesn't show it correctly).