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



我有一个带有组合框(CMBPORT#)的表单,可以选择多达8个串行端口。我想首先清除每个项目列表,并在当前可用的系统端口中填充它们,然后将选项" OFF"添加到每个列表中。最后,根据String spname()保存的默认值设置每个组合框。我创建了一个GroupBox(Gbox1),并将每个CMBPort拖到它上,但我不确定如何引用其上的控件。我正在使用VB 2015。

您可以帮助使用vb.net代码以更有效地使用循环(每个或类似)吗?

    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

循环是一种非常有用的工具。我在这里提出了一些代码,以便您可以得到这个想法,但是我正在努力工作,因此您可能必须对此代码应用一些修复程序,以使其按照您的需求进行工作。

主要想法是您不必再编写一行。如果您将相同的操作乘以几行代码,则为将来创造潜在的问题。循环和潜艇确实有助于防止这种问题。

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

您不应该考虑到此方程式中的效率,因为仅在负载时就不会始终调用此操作。我的意思是:您应该始终尽力而为,但是优化有时是良好,可读代码的敌人。

最新更新