如何使用循环更新一组组合框

时间:2019-03-06 17:06:22

标签: vb.net

我有一个带有组合框(cmbPort#)的表格,最多可以选择8个串行端口。我想首先清除每个项目的列表,用当前可用的系统端口填充它们,然后将选项“关”添加到每个列表。最后,根据保存在字符串spName()中的默认值设置每个组合框。我创建了一个GroupBox(gBox1)并将每个cmbPort拖到它上面,但是我不确定如何引用它上的控件。我正在使用VB 2015。

您可以帮助VB.NET代码使用循环(“ For Each”或类似的循环)来更有效地做到这一点吗?

    Private Sub frmProp_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    cmbPort1.Items.Clear()
    ...
    cmbPort8.Items.Clear()

    For Each sp As String In My.Computer.Ports.SerialPortNames
        cmbPort1.Items.Add(sp)
        ...
        cmbPort8.Items.Add(sp)
    Next

    cmbPort1.Items.Add("Off")
    ...
    cmbPort8.Items.Add("Off")

    cmbPort1.Text = spName(1)
    ...
    cmbPort8.Text = spName(8)

End Sub

1 个答案:

答案 0 :(得分:0)

循环是一个非常有用的工具。我在这里介绍了一些代码,以便您可以理解,但是我正在使用IDE,因此您可能必须对此代码进行一些修复才能使其按需工作。

主要思想是,您不必多次写一行。如果在几行代码上乘以相同的操作,则会为将来带来潜在的问题。循环和子程序确实有助于防止此类问题。

Private Sub frmProp_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'This is for later
    Dim cmbIndex As Integer = 1

    'You basically do the same operations for every Combobox in your list, son only one loop needed
    For Each cmbPort As ComboBox In {cmbPort1, cmbPort2, cmbPort3 [...] cmbPort8} 'this is a way to declare an array
        'Clear
        cmbPort.Items.Clear()

        'Add SerialPortNames
        For Each sp As String In My.Computer.Ports.SerialPortNames
            cmbPort.Items.Add(sp)
        Next

        'Add "Off"
        cmbPort.Items.Add("Off")

        'This last one is a little bit trickier because you want to match numbers
        'This is the place where you get errors when something doesn't go as planned
        'If you need to keep it inside the loop here's a way to achieve that, but honestly I would't do that
        'Instead I would suggest that you take this part out of the loop and do it manually
        If spName(cmbIndex) IsNot Nothing Then cmbPort.Text = spName(cmbIndex)
        cmbIndex += 1
    Next
End Sub

您不应该在效率方程中考虑效率,因为不会一直调用此操作,而只会在负载下调用。我的意思是:您应该始终以最好的方式来做事情,但是优化有时是好的,易读的代码的敌人。