Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

vb.net - Setting same SelectedIndex value for multiple combobox

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...