VB.NET中的多个IF条件

时间:2015-11-07 09:18:20

标签: vb.net

请帮我缩短以下代码:

If Val(TB.Text) = 0 Then
    OvalShape1.BackColor = Color.Gray
ElseIf Val(TB.Text) = 1 Then
    OvalShape1.BackColor = Color.Lime
ElseIf Val(TB.Text) = 2 Then
    OvalShape1.BackColor = Color.Red
ElseIf Val(TB.Text) = 3 Then
    OvalShape1.BackColor = Color.White
End If

1 个答案:

答案 0 :(得分:1)

这样就可以了:

Dim colors As System.Drawing.Color() = {Color.Gray, Color.Lime, Color.Red, Color.White}

OvalShape1.BackColor = colors(Val(TB.Text))

但最好添加一些验证来覆盖导致运行时错误的TB.Text中的无效输入。这是更长的,但更好的代码:

Dim colors As System.Drawing.Color() = {Color.Gray, Color.Lime, Color.Red, Color.White}
Dim value as Integer

value = Val(TB.Text)
If value >= 0 And value <= colors.GetUpperBound(0) Then
    OvalShape1.BackColor = colors(value)
End If