讓我試着用最簡單的方式來描述我的問題:我有combobox1和combobox2。我希望實現兩件事情:vb.net,combobox.datasource會改變選定的索引?
Combox1綁定到list1(字符串列表)。當用戶選擇list1中的一個項目時,將從數據庫獲取list2(一個字符串列表),並將組合框綁定到list2。
如果用戶在combobox1中指定了text1並在combobox2中指定了text2,那麼無論綁定列表如何,這兩個值都將顯示在組合框中。
因此,我將DropDown設置爲dropdpwnstyle到兩個組合框。
Public Sub New(Optional ByVal text1 As String = "", Optional ByVal text2 As String = "")
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.combobox1.selectedText=text1
Me.combobox2.selectedText=text2
End Sub
Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
BindComboBox1()
End Sub
Private Sub BindComboBox1()
'm_list1 is a list of string
combobox1.DataSource = m_list1
End Sub
Private Sub GetCombobox2()
'based on the selected item in combobox1, m_list2 which is a list of string is obtained
ComboBox2.DataSource = m_list2
End Sub
Private Sub combobox1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles combobox1.SelectedIndexChanged
If combobox1.SelectedIndex <> -1 Then
GetCombobox2()
End If
End Sub
當我調試,我注意到兩兩件事:
Me.combobox1.SelectedText =文本1之後,實際上,Me.combobox1.SelectedText = 「」。但是Me.combobox1.Text = text1。這是因爲combobox1.SelectedIndex = -1?
Combobox1.datasource = m_list1將combobox1.selectedindex從-1更改爲0.這將觸發combobox.selectedIndexchange事件。
因此,上述代碼的結果是實現了目標1,但目標2從未實現。 combobox1.selected索引始終爲0,combobox2.selected索引始終爲0。