2017-05-25 50 views
-2

我使用vb.net 2008构建应用程序。我有一个包含远程设备IP地址的50个文本框的表单,如果ping设备正常,则文本框的背景颜色为绿色,否则为红色。我用的是如果功能如下:如何减少50如果函数按For ... Next循环使用超过50个文本框?

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如果功能,因为这使得代码很长,你能不能帮我缩短代码For ... Next循环。 谢谢你的帮助。

+0

这看起来像一个功能的工作。 – Carcigenicate

+1

编写你认为你应该的循环,然后如果它不起作用,我们可以帮助你修复它。如果你不知道如何编写'For'或'For Each'循环,请阅读这个主题。我们在这里帮助您解决特定问题,而不是为您编写代码。如果您还没有尝试写代码,那么您还没有遇到特定的问题。 – jmcilhinney

回答

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秒,我认为这是一个相当长的时间。有没有办法减少代码执行时间?

+0

如果您问这是一个问题,它将是[修改使用普通ping方法使用Async ping方法的VB.Net程序](https://stackoverflow.com/q/30400219/1115360)的副本。 –

相关问题