有没有办法同时找到几个变量的长度?

时间:2015-03-05 13:05:55

标签: vb.net visual-studio-2010

按下按钮时,我试图检测空文本框。为此,我为每个变量使用if语句,如下所示:

If Len(variable.Text) = 0 Then 
   Messagebox.Show("please fill in all fields.")
End If 

是否有更有效的方法可以检测所有文本框中的字符串长度是否同时等于零?或者,如果有人想建议一个更好的方法,也将被赞赏。谢谢。

2 个答案:

答案 0 :(得分:1)

如果文本框的形式与验证按钮

相同,则可以这样做
Dim ctrl As Control
For Each ctrl In Me.Controls ' panelname.controls etc
    If (ctrl.GetType() Is GetType(TextBox)) Then
        If Trim(ctrl.Text) = "" Then
            MessageBox.Show("please fill in all fields.")
            Exit Sub
        End If
    End If
Next

OR

Dim ctrl As Control
Dim count As Integer
count = 0
For Each ctrl In Me.Controls ' panelname.controls etc
    If (ctrl.GetType() Is GetType(TextBox)) Then
        If Trim(ctrl.Text) = "" Then count += 1
        'you can add exceptions by textbox name also by getting ctrl.Name
    End If
Next
If count > 0 Then
    MessageBox.Show("please fill in all fields.")
End If

答案 1 :(得分:0)

这是要走的路。 (:

如果你想检查所有文本框是否为空(或换句话说:是否可以将某些文本框留空),你可以使用以下内容:

'if some textboxes can be empty
IF a="" AND b="" AND c="" Then Messagebox.Show("please fill in all fields.")

'if no textbox can be empty
IF a="" OR b="" OR c="" Then Messagebox.Show("please fill in all fields.")
相关问题