儘管它在VB中,但是關於Changing Combobox Text in the SelectedIndexChanged
Event的這篇博文更詳細地介紹了爲什麼您需要使用委託作爲解決方法來更改ComoboBox文本。總之,.NET試圖阻止可能發生的無限循環,因爲當對Text屬性進行更改時,.NET將嘗試將該新值與當前項目匹配併爲您更改索引,從而觸發SelectedIndexChanged事件再次。
人們來這裏尋找一個VB實現代表的可以參考下面的代碼
'Declares a delegate sub that takes no parameters
Delegate Sub ComboDelegate()
'Loads form and controls
Private Sub LoadForm(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
ComboBox1.Items.Add("This is okay")
ComboBox1.Items.Add("This is NOT okay")
ResetComboBox()
End Sub
'Handles Selected Index Changed Event for combo Box
Private Sub ComboBoxSelectionChanged(sender As System.Object, e As System.EventArgs) _
Handles ComboBox1.SelectedIndexChanged
'if option 2 selected, reset control back to original
If ComboBox1.SelectedIndex = 1 Then
BeginInvoke(New ComboDelegate(AddressOf ResetComboBox))
End If
End Sub
'Exits out of ComboBox selection and displays prompt text
Private Sub ResetComboBox()
With ComboBox1
.SelectedIndex = -1
.Text = "Select an option"
.Focus()
End With
End Sub
這對我工作,謝謝! – cchamberlain 2012-03-15 20:18:33