我正在使用与此类似的代码,用数据库中的项填充组合框。显示工作正常,但当我尝试获取combobox.SelectedValue
它返回DataRowView,我需要一个整数。显然这是因为我没有将值转换为整数,但函数CInt(cboPosition.SelectedValue)
抛出InvalidCastException。有什么方法可以让ValueMember的类型成为整数?
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
答案 0 :(得分:2)
您需要在SQL中选择ID
和Text
字段。
如果您确实选择了ID
,则可以使用MsgBox TypeName(cboPosition.SelectedValue)
来确定所选值的类型。这可能有助于您进行调试。
编辑:如果SelectedValue
返回DataRowView
,您可以像这样访问ID
字段:
Dim myDataRowView As DataRowView = DirectCast(cboPosition.SelectedValue, DataRowView)
Dim myId as Integer = CInt(myDataRowView("CustomerID"))
至于为什么SelectedValue
会返回DataRowView
,虽然设置了正确的ValueMember
,但我不知道......
EDIT2:我找到SelectedValue
返回整行但不仅仅ValueMember
的原因:你have to set the properties in the "right" order,即:
uxCustomerName.DisplayMember = "CustomerName"
uxCustomerName.ValueMember = "CustomerID"
uxCustomerName.DataSource = dt
(首先DisplayMember
和ValueMember
,然后 DataSource
。)