我创建了这段代码,看看有多少文本框输入了一些东西,然后在一个消息框中显示总数,我想知道我是否可以将我的下面的代码设置得更小可以将它放在一个循环中?
Dim TotalRooms = 0
If String.IsNullOrEmpty(txtRoom1.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom2.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom3.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom4.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom5.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom6.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom7.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom8.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom9.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
If String.IsNullOrEmpty(txtRoom10.Text) Then
TotalRooms = TotalRooms + 0
Else
TotalRooms = TotalRooms + 1
End If
MessageBox.Show(TotalRooms)
答案 0 :(得分:0)
如果String.IsNullOrEmpty(Text)
删除条件,则可以删除一半代码,因为否则只会增加TotalRooms
。
If Not String.IsNullOrEmpty(txtRoomX.Text) Then
TotalRooms += 1
End If
答案 1 :(得分:0)
如您所述,您可以通过循环解决此问题:
Dim TotalRooms = 0
For Each c In Controls.OfType(Of TextBox)
If Not String.IsNullOrEmpty(c.Text) Then TotalRooms += 1
Next
MessageBox.Show(TotalRooms)
答案 2 :(得分:0)
假设您的所有txtRooms
个文本框都遵循相同的命名约定,这应该有效..
For i As Integer = 1 To 10
Dim tempTxtBox As Control() = Controls.Find("txtRoom" & i.ToString, False)
If Not String.IsNullOrEmpty(DirectCast(tempTxtBox(0), TextBox).Text) Then TotalRooms += 1
Next
您只需将For
语句中的数字10更改为您拥有的房间数。
只是一个小小的提示。如果您为多个客户编写此代码,您可能最好在代码的开头创建一个常量,这样如果您有其他代码作用于所有房间,您只需要更改一个地方的房间数量。