Pulling a value from a databound (lookup table) combobox? How?
Posted on 2004-04-21
I have a Windows Form application that has several ComboBox controls on it. (Let's just deal with one for now). My SQL database has several lookup tables related to products and versions of our software, something like this (fake - for example only):
So I bind the ComboBox control to the data like this:
'Populate the Product Dropdown
cmbProduct.DataSource = Database.GetProducts.Tables(0) 'Database is a class, the GetProducts Function returns a DataSet
cmbProduct.DisplayMember = "Product_Name"
cmbProduct.ValueMember = "Product_ID"
Great! So now my ComboBox is loaded and displaying the names of the products. This works just fine.
Now, I have a second combobox, that lists the versions of a given product. It might look like this:
Version_ID Product_ID Version Name
1 5 1.0
2 5 2.0
3 10 1.0.1
4 10 1.0.2
5 16 2.0
6 16 3.0
I need to pull the Versions by supplying the Product_ID from the Product Combobox. (i.e. SELECT * FROM Versions WHERE Product_ID = 5)
Private Sub cmbProduct_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbProduct.SelectedIndexChanged
'Populate the Version Dropdown
If cmbProduct.SelectedIndex <> -1 Then
cmbVersion.DataSource = Database.GetProductVersions(CType(cmbProduct.SelectedValue, Integer)).Tables(0)
cmbVersion.DisplayMember = "Product_Name"
cmbVersion.ValueMember = "Product_ID"
OK, SO HERE IS MY PROBLEM.
I can't figure out how to pull the "selected value" from the Combobox. There is indeed a property called .SelectedValue, but it returns a System.Object, and when I try to do a CTYPE(objCombo.SelectedValue, Integer), it throws an error, "Cast from type 'DataRowView' to type 'Integer' is not valid."
All I really want to know is what value Product_ID is related to the selected item. I suppose I can pull the ComboBox.Text value and jump through hoops to reverse engineer that value back out, but that seems to defeat the purpose. Sorry guys, I'm used to ASP.NET where I can just request the SelectedItem.Value and it gives it to me.
Any help would be greatly appreciated.