views:

9

answers:

1

I am using code similar to this to populate a combobox with items from a database. The display works fine, but when I try to get the combobox.SelectedValue it is returning a DataRowView, where I need an integer. Obviously this is becuase I haven't casted the value to an integer, but the function, CInt(cboPosition.SelectedValue) is throwing an InvalidCastException. Is there any way that I can get the ValueMember's type to be an Integer?

Dim cn As New SqlConnection(CreditDisputesLogConn)
    Dim cmd As New SqlCommand("CustomersLookup", cn)
    Dim da As New SqlDataAdapter(cmd)
    cmd.CommandType = CommandType.StoredProcedure
    Try
        Dim dt As New DataTable
        da.Fill(dt)
        uxCustomerName.DataSource = dt
        uxCustomerName.DisplayMember = "CustomerName"
        uxCustomerName.ValueMember = "CustomerID"
        uxCustomerName.SelectedIndex = -1
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        cn.Close()
        cn.Dispose()
    End Try
+1  A: 

You need to select both fields ID and Text in your SQL.

If you did select ID, you can use MsgBox TypeName(cboPosition.SelectedValue) to determine the type of the selected value. This might help you with debugging.


EDIT: If SelectedValue returns a DataRowView, you can access the ID field like this:

Dim myDataRowView As DataRowView = DirectCast(cboPosition.SelectedValue, DataRowView)
Dim myId as Integer = CInt(myDataRowView("CustomerID"))

As to why SelectedValue returns the DataRowView although a correct ValueMember is set, I have no idea...


EDIT2: I found the reason why SelectedValue returns the whole row instead of just the ValueMember: You have to set the properties in the "right" order, i.e.:

    uxCustomerName.DisplayMember = "CustomerName"
    uxCustomerName.ValueMember = "CustomerID"
    uxCustomerName.DataSource = dt

(First DisplayMember and ValueMember, then DataSource.)

Heinzi
As I said, the code above is only similar. The stored procedure I'm using _does_ return the ID and Description fields; that part works fine. The issue is that the type of the SelectedValue is `DataRowView`
Caleb Thompson
I edited the answer to show the actual code for the lookup that I'm using.
Caleb Thompson
Just to make sure: You *are* using `SelectedValue` and not `SelectedItem`, right? I've updated my answer.
Heinzi
Updated my answer with (what I believe to be) the final solution.
Heinzi
Excellent. That fixed it. Thank you
Caleb Thompson