如何使用DataTable作为其DataSource从ComboBox获取整数值

时间:2010-06-23 23:39:03

标签: vb.net casting datatable valuemember

我正在使用与此类似的代码,用数据库中的项填充组合框。显示工作正常,但当我尝试获取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

1 个答案:

答案 0 :(得分:2)

您需要在SQL中选择IDText字段。

如果您确实选择了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

(首先DisplayMemberValueMember然后 DataSource。)