In principle the validation must make it control to control, since for each one the validations can be different (besides checking that the textbox is not empty, you could also check that the entry is a number, for example). The usual way is to subscribe to the events Validating
and Validated
of the control and perform the validation there.
On the other hand, instead of using a MessageBox
, it is best to add a ErrorProvider
to your form, and in case the control validation fails add the error there. It would be something like this:
private void textbox_Validating(object sender,System.ComponentModel.CancelEventArgs e)
{
if(textbox.text == "" )
{
e.Cancel = true;
textbox.Select(0, textBox1.Text.Length);
errorProvider1.SetError (textBox1,"Debe introducir el nombre");
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
errorProvider1.SetError(textbox, "");
}
This means that at the moment when the TextBox
loses focus, the field is validated, and if it is not correct, an error symbol appears next to the problem.
If what you want is that all the controls are validated when you press a button (for example, when saving the file) what you should do is put the property AutoValidate
of the form to Disabled
, for example putting this in the form's constructor:
this.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
Then, in the save button, the code would be something like this:
private void buttonGuardar_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Enabled))
{
//Todo es correcto, guardamos los datos
}
else
{
MessageBox.Show("Faltan algunos campos por rellenar");
}
}
In order for this to work, you must have done in all the controls what you indicated before Validating
and Validated
I hope this helps you.
Edit
To include what he says @PabloSimonDiEstefano, the example I put in my answer deals with a single TextBox
. If you want to validate several with the same code, you should first point all events Validating
of all TextBox
to the same managed, and in it get the first thing that TextBox
originated:
private void textboxes_Validating(object sender,System.ComponentModel.CancelEventArgs e)
{
TextBox tb = (TextBox) sender;
if(tb.text == "" )
{
e.Cancel = true;
tb.Select(0, tb.Text.Length);
errorProvider1.SetError (tb ,"Debe introducir el nombre");
}
}
private void textboxes_Validated(object sender, System.EventArgs e)
{
TextBox tb = (TextBox) sender;
errorProvider1.SetError(tb, "");
}