如何使用 DataTable 作为数据源从 ComboBox 获取整数值
我正在使用与此类似的代码来使用数据库中的项目填充组合框。显示工作正常,但是当我尝试获取 combobox.SelectedValue
时,它返回一个 DataRowView,其中我需要一个整数。显然这是因为我没有将值转换为整数,但是函数 CInt(cboPosition.SelectedValue)
抛出了 InvalidCastException。有什么方法可以让 ValueMember 的类型成为 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在 SQL 中选择
ID
和Text
字段。如果您确实选择了
ID
,则可以使用MsgBox TypeName(cboPosition.SelectedValue)
来确定所选值的类型。这可能会帮助您进行调试。编辑:如果
SelectedValue
返回DataRowView
,您可以像这样访问ID
字段:至于为什么
SelectedValue
返回DataRowView
虽然设置了正确的ValueMember
,但我不知道...EDIT2:我找到了
SelectedValue
返回整行的原因仅ValueMember
:您必须在“right”中设置属性" 顺序,即:(首先是
DisplayMember
和ValueMember
,然后DataSource
。)You need to select both fields
ID
andText
in 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
SelectedValue
returns aDataRowView
, you can access theID
field like this:As to why
SelectedValue
returns theDataRowView
although a correctValueMember
is set, I have no idea...EDIT2: I found the reason why
SelectedValue
returns the whole row instead of just theValueMember
: You have to set the properties in the "right" order, i.e.:(First
DisplayMember
andValueMember
, thenDataSource
.)