问题
I populated my combobox1 with this code in load
sql = "select name1,id1 from table1"
da = New Odbc.OdbcDataAdapter(sql, con)
da.Fill(ds, "cbtbl1")
ComboBox1.DataSource = ds.Tables("cbtbl1")
ComboBox1.DisplayMember = ds.Tables("cbtbl1").Columns("name1").Caption
I have my 2nd combobox2 related to combobox1. I inserted this code in combobox1 selectedvaluechanged
. This to change to value of combobox2 based on their related ids
sql = "select name2,id2 from table2 where id1=" & ???????
da = New Odbc.OdbcDataAdapter(sql, con)
da.Fill(ds, "cbtbl2")
ComboBox2.DataSource = ds.Tables("cbtbl2")
ComboBox2.DisplayMember = ds.Tables("cbtbl2").Columns("name2").Caption
In my code i have question marks. It supposed to be the id of table1 which i don't know how to get :( or what to put
回答1:
You should set the ValueMember
of Combobox1 to be the ID you retrieved from the database and the use the SelectedValue
property to retrieve the ID of the selected item.
I don't think it's gonna work unless you specify the ValueMember
property when you databind Combobox1, so don't forget to do that first.
OK, I knocked something together quickly with a database I am working on at the moment (it's OLEDB, but shouldn't matter for this)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Dim ds As New DataSet()
Dim test As New OleDbDataAdapter("SELECT [ID], [名前] FROM [Tレイヤ管理]", DBConnections.PrimaryAccessDBConnection)
Call test.Fill(ds, "testTable")
Me.ComboBox1.DataSource = ds.Tables("testTable")
Me.ComboBox1.ValueMember = "ID"
Me.ComboBox1.DisplayMember = "名前"
AddHandler Me.ComboBox1.SelectedValueChanged, AddressOf Something
End Sub
Private Sub Something(sender As Object, e As EventArgs)
Call MessageBox.Show(String.Format("ID {0}", Me.ComboBox1.SelectedValue))
End Sub
I get the ID showing just fine with this.
UPDATE:
If this still doesn't work then you can get the selected item this way:
Private Sub Something(sender As Object, e As EventArgs)
Dim selectedItem As DataRowView = CType(Me.ComboBox1.SelectedItem, DataRowView)
Call MessageBox.Show(String.Format("ID {0} Name {1}", New Object() {selectedItem("ID"), selectedItem("名前")}))
End Sub
来源:https://stackoverflow.com/questions/15426218/vb-net-combobox-population-getting-index-of-the-1st-combobox