문제

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
도움이 되었습니까?

해결책

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.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top