我使用vb.net 2008来构建应用程序。我有一个包含50个文本框的表单,其中包含远程设备的IP地址,如果ping设备良好,则文本框的背景颜色为绿色,否则为红色。我使用If函数如下:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If My.Computer.Network.Ping(TextBox1.Text) Then
TextBox1.BackColor = Color.Green
Else
TextBox1.BackColor = Color.Red
End If
If My.Computer.Network.Ping(TextBox2.Text) Then
TextBox2.BackColor = Color.Green
Else
TextBox2.BackColor = Color.Red
End If
.
.’ The if functions of the Textbox3 to the Textbox49
.
If My.Computer.Network.Ping(TextBox50.Text) Then
TextBox50.BackColor = Color.Green
Else
TextBox50.BackColor = Color.Red
End If
End Sub
End Class
对于50个文本框,我必须使用50 If函数,因为这会使代码很长,你能帮我用For ... Next循环来缩短代码。 谢谢你的帮助。
答案 0 :(得分:0)
感谢您的帮助和建议,我用这段代码解决了我的问题:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tbArray() As TextBox = New TextBox() {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7, TextBox8, TextBox9, TextBox10, TextBox11, TextBox12, TextBox13, TextBox14, TextBox15, TextBox16, TextBox17, TextBox18, TextBox19, TextBox20, TextBox21, TextBox22, TextBox23, TextBox24, TextBox25, TextBox26, TextBox27, TextBox28, TextBox29, TextBox30, TextBox31, TextBox32, TextBox33, TextBox34, TextBox35, TextBox36, TextBox37, TextBox38, TextBox39, TextBox40, TextBox41, TextBox42, TextBox43, TextBox44, TextBox45, TextBox46, TextBox47, TextBox48, TextBox49, TextBox50}
Dim i As Short
For i = 0 To 49
If My.Computer.Network.Ping(tbArray(i).Text) Then
tbArray(i).BackColor = Color.Green
Else
tbArray(i).BackColor = Color.Red
End If
Next
End Sub
但是出现了另一个问题,整个代码大约需要35秒,我认为这已经很长时间了。有没有办法减少代码执行时间?