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
IDandTextin your SQL.If you did select
ID, you can useMsgBox TypeName(cboPosition.SelectedValue)to determine the type of the selected value. This might help you with debugging.EDIT: If
SelectedValuereturns aDataRowView, you can access theIDfield like this:As to why
SelectedValuereturns theDataRowViewalthough a correctValueMemberis set, I have no idea…EDIT2: I found the reason why
SelectedValuereturns the whole row instead of just theValueMember: You have to set the properties in the “right” order, i.e.:(First
DisplayMemberandValueMember, thenDataSource.)