Validations of fields in C #

5

I am learning and recently in a desktop application with which we work in the room we enter 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 in if it is longer , since we had to validate a form of a point of sale, which has many more fields to validate.

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

I understand that it is possible, but I do not know how to do it.

    
asked by Jeff 05.03.2017 в 06:19
source

3 answers

13

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, "");
}
    
answered by 06.03.2017 в 09:13
5

You could create a control of your own that inherits the control to validate, and program a validation method.

Example:

public class MiTextBox : TextBox 
{
    public bool EsValido() 
    {
        // El método IsNullOrWhiteSpace devuelve TRUE cuando el parametro string pasado es NULL o tiene una cadena de caracteres de espacios o vacía.
        // Usamos el operador ! para invertir el bool devuelvo. 
        return !string.IsNullOrWhiteSpace(this.Text);
    }
}

Once you have created your control, you can compile the project and it will appear in the ToolBox.

Use this as text box, in which it comes, and for validations you only have to call the method:

//Si EsValido devuelve false, mostrar el MessageBox
if(!textbox.EsValido())
{
   MessageBox.Show("hacen falta campos por llenar")
}

You should keep in mind that in your method, you can make all the validations that you think are convenient.

In this way you create a control that you can reuse.

    
answered by 05.03.2017 в 16:20
1

If you want to do it all at once, you have 1000 textbox in a form (exaggerate, you know ...) and to validate them is a world ... you can do this. Create a method like that.

 bool validarTextBoxs()
    {
        foreach (Control item in this.Controls)
        {
            try
            {
                if (item is TextBox)
                {
                    //Codigo comprobacion  de textbox
                    if (item.Text == "")
                    {
                        MessageBox.Show("Hay campos vacios");
                        item.Focus();
                        return false;
                    }
                }
                else if (item is RichTextBox)
                {
                    //codigo comprobacion de richtextbox
                    if (item.Text == "")
                    {
                        MessageBox.Show("Hay campos vacios");
                        item.Focus();
                        return false;
                    }
                }
                else if (item is ComboBox)
                {
                    if (item.Text == "")
                    {
                        MessageBox.Show("Debes seleccionar un item");
                        item.Focus();
                        return false;
                    }
                }
            }
            catch { }
        }
        return true;
    }     

Good luck!

    
answered by 07.03.2017 в 20:55