循环遍历多个列表框控件并检查每个列表框的选定索引

时间:2016-02-11 11:44:22

标签: vb.net winforms

我正在使用以下代码尝试遍历WinForm上面板中的所有ListBox控件。我想检查其中是否有SelectedIndex高于0.如果有,我想将数组中的布尔值设置为True,否则将其设置为False:< / p>

Dim i As Integer = -1
For Each cntrl As Control In Form1.Panel3.Controls
    If TypeOf cntrl Is ListBox Then
        i = i + 1
        If cntrl.selectedindex <> 0 Then
            ReportArray(i) = True
        Else
            ReportArray(i) = False
        End If
    End If
Next

我遇到的问题是cntrl.selectedindex无效,因为.selectedindex已被选中,因为它不是Windows.Forms.Control的成员

如何将其视为ListBox

1 个答案:

答案 0 :(得分:2)

首先尝试将cntrl转换为列表框

Dim i As Integer = -1

For Each cntrl As Control In Form1.Panel3.Controls
    If TypeOf cntrl Is ListBox Then
        Dim TmpCntrl As ListBox = TryCast(cntrl, ListBox)

        i = i + 1
        If TmpCntrl.selectedindex <> 0 Then
            ReportArray(i) = True
        Else
            ReportArray(i) = False
        End If
    End If
Next