问题
I have a form where i have 23 Comboboxes. Writing SelectedIndex=-1 for every combobox will definitely work but i want to know whether there's any other way of doing it as done in below given example. ?
For Each ctl As Control In (GroupBox1.Controls)
If TypeOf ctl Is TextBox Then
ctl.Text = ""
End If
Next
i tried this,If TypeOf ctl Is ComboBox Then
ctl.selectedIndex=-1
End If
but it doesn't works. Please help me out.
回答1:
In your example your ctl variable is a Control and not a Combobox so it does not have the SelectIndex property - though you could have casted it back with DirectCast(ctl, Combobox).
For Each ctl As Control In (GroupBox1.Controls)
If TypeOf ctl Is Combobox Then
DirectCast(ctl, Combobox).SelectedIndex = -1
End If
Next
Or create a loop of type specific control for your loop. No need to check type here.
Dim cbs = GroupBox1.Controls.OfType(Of Combobox)()
For Each cb In cbs
cb.SelectedIndex = -1
Next
来源:https://stackoverflow.com/questions/26441096/setting-same-selectedindex-value-for-multiple-combobox