c# – Field validations in C #

Question:

I am learning and recently in a desktop application with which we work in the classroom we entered the subject of validations.

We were taught something like this:

if(textbox.text == "" ){
  MessageBox.Show("hacen falta campos por llenar")
}

This is an example that we did in class itself, it is longer , since a form of a point of sale had to be validated, which has many more fields to validate.

My question is: is there a way to save code and make the validations simpler?

I understand that it is possible, but I don't know how to do it.

Answer:

In principle, the validation should be done control by control, since for each one the validations can be different (in addition to checking that the textbox is not empty, you could also check that the input is a number, for example). The usual way is to subscribe to the Validating and Validated events of the control and perform the validation there.

On the other hand, instead of using a MessageBox , it is best to add an ErrorProvider to your form, and in the event that 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 the moment the TextBox loses focus, the field is validated, and if it is not correct, an error symbol appears next to it indicating the problem.

If you want all the controls to be validated when pressing a button (for example, when saving the tab), what you should do is set the AutoValidate property of the form to Disabled , for example by 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");
    }
}

For this to work you have to have done in all the controls what I indicate before Validating and Validated

I hope this helps.

Edit

To include what @PabloSimonDiEstefano comments, the example I put in my answer deals with a single TextBox . If you wanted to validate several with the same code, first you would have to point all the Validating events of all the TextBox to the same handle, and in it obtain the first thing that the 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, "");
}
Scroll to Top