2012-08-26 22 views
6

Tengo 10 cuadros de texto, ahora quiero comprobar que ninguno de ellos está vacío cuando se hace clic en un botón. Mi código es:Validar múltiples cuadros de texto usando errorprovider

if (TextBox1.Text == "") 
{ 
    errorProvider1.SetError(TextBox1, "Please fill the required field"); 
} 

¿Hay alguna manera de que puedo comprobar todos los cuadros de texto a la vez, en lugar de escribir para cada individuo?

+0

Eso es casi seguro Formularios de Windows, no asp.net. – Adam

Respuesta

20

Sí, la hay.

En primer lugar, es necesario obtener todos los cuadros de texto en forma de una secuencia, por ejemplo a esto:

var boxes = Controls.OfType<TextBox>(); 

A continuación, puede iterar sobre ellos, y establecer el error en consecuencia:

foreach (var box in boxes) 
{ 
    if (string.IsNullOrWhiteSpace(box.Text)) 
    { 
     errorProvider1.SetError(box, "Please fill the required field"); 
    } 
} 

Recomendaría usar string.IsNullOrWhiteSpace en lugar de x == "" o + string.IsNullOrEmpty para marcar los cuadros de texto llenos de espacios, pestañas y similares con un error.

1

no podría ser una solución óptima, pero esto también debería funcionar

public Form1() 
    { 
     InitializeComponent(); 
     textBox1.Validated += new EventHandler(textBox_Validated); 
     textBox2.Validated += new EventHandler(textBox_Validated); 
     textBox3.Validated += new EventHandler(textBox_Validated); 
     ... 
     textBox10.Validated += new EventHandler(textBox_Validated); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     this.ValidateChildren(); 
    } 

    public void textBox_Validated(object sender, EventArgs e) 
    { 
     var tb = (TextBox)sender; 
     if(string.IsNullOrEmpty(tb.Text)) 
     { 
      errorProvider1.SetError(tb, "error"); 
     } 
    } 
1

Editar:

var controls = new [] { tx1, tx2. ...., txt10 }; 
foreach(var control in controls.Where(e => String.IsNullOrEmpty(e.Text)) 
{ 
    errorProvider1.SetError(control, "Please fill the required field"); 
} 
Cuestiones relacionadas