【问题标题】:How to reduce 50 If functions by For ... Next loop using over 50 textboxes? [duplicate]如何通过 For ... Next 循环使用超过 50 个文本框减少 50 个 If 函数? [复制]
【发布时间】:2017-05-25 02:39:21
【问题描述】:

我使用 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 循环缩短代码吗? 感谢您的帮助。

【问题讨论】:

  • 这看起来像是一个函数的工作。
  • 编写您认为应该的循环,如果它不起作用,我们可以帮助您修复它。如果您不知道如何编写 ForFor Each 循环,请阅读该主题。我们在这里帮助解决特定问题,而不是为您编写代码。如果您还没有尝试编写代码,那么您还没有遇到特定问题。

标签: vb.net


【解决方案1】:

感谢您的帮助和建议,我用这段代码解决了我的问题:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
相关资源
最近更新 更多