VB.NET:从DB中的列设置组合框文本,但是从不同列设置值

时间:2017-02-28 06:12:34

标签: vb.net combobox

我是新手,在我长达数小时的搜索中找不到答案,所以......

任何人都可以告诉我如何让组合框从数据库中的一列显示文本,但在选择时传递一个不同的值 - VB.NET?

例如 - 我有一个显示一列名字的组合框,在同一个表中有一列数字。我希望名称显示在组合框中,但是来自不同列的值,其中包含要在选中时传递给查询的数字。

这会填充组合框:

       Private Sub GetTeamMembers()
    SQL.ExecQuery("SELECT distinct ACCPIN.CPIN, (CFIRST + CLAST) as TMNAME " & _
                  " FROM         ACCDTL LEFT OUTER JOIN " & _
                  " ACCPIN ON ACCDTL.CPIN = ACCPIN.CPIN " & _
                  " Order by TMNAME")

    ''Add to combo box
    If String.IsNullOrEmpty(SQL.Exception) Then
        For Each dr As DataRow In SQL.SQLDS.Tables(0).Rows
            cbxTeamMembers.Items.Add(dr("CPIN").ToString)
        Next
    End If

End Sub

因此,CPIN是保存我想要传递给下一个查询的值的列。但我希望能够显示专栏#TM; TMNAME"在组合框中,但在我选择组合框中的文本时传递值CPIN。

使用当前的组合框选择运行:

    Private Sub cbxTeamMembers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxTeamMembers.SelectedIndexChanged
    GetTMAccess(cbxTeamMembers.Text)
End Sub

......然后:

Private Sub GetTMAccess(ByVal TeamMember As String)



    ''Run Query for access group pins
    SQL.ExecQuery("SELECT ACCPIN.CFIRST AS FIRSTNAME " & _
                  ", ACCPIN.CLAST AS LASTNAME " & _
                  ", ACCPIN.CPIN AS PIN " & _
                  ", ACCPIN.CSHIFT AS SHIFT " & _
                  ", ACCPIN.CRANK AS TMRANK " & _
                  ", ACCDTL.CACCESSID AS ACCESS " & _
                  "FROM ACCDTL INNER JOIN " & _
                  "ACCPIN ON ACCDTL.CPINID = ACCPIN.CPIN " & _
                  "WHERE (ACCDTL.CPIN = '" & TeamMember & "') " & _
                  " ORDER BY FIRSTNAME")



    ''Halt & Report on errors
    If Not String.IsNullOrEmpty(SQL.Exception) Then MsgBox(SQL.Exception) : Exit Sub

    ''Fill The Datagridview with the query results
    If SQL.RecordCount > 0 Then
        dvgTMAccess.DataSource = SQL.SQLDS.Tables(0)

    End If
End Sub

2 个答案:

答案 0 :(得分:0)

绑定控件并将DisplayMember设置为要显示其值的列的名称,并将ValueMember设置为要由{{返回的值的列的名称1}} SelectedValue的属性。在你的情况下,这可能意味着:

ComboBox

请注意With cbxTeamMembers .DisplayMember = "TMNAME" .ValueMember = "CPIN" .DataSource = SQL.SQLDS.Tables(0) End With 最后设置的事实,这不是必需的,但是可取的。这样:

DataSource

然后会变成这样:

GetTMAccess(cbxTeamMembers.Text)

答案 1 :(得分:0)

可能有一种更简单的方法可以做到这一点,但这是我的同事为解决这个问题而实施的方法。

首先,创建一个新类来存储您的值:

Public Class ComboItem
    Public Display As String
    Public Value As String

    Public Sub New(ByVal _display As String, ByVal _value As String)
        Display = _display
        Value = _value
    End Sub

    Public Overrides Function ToString() As String
        Return Display
    End Function
End Class

然后,在填充组合框时,请执行以下操作:

cbxTeamMembers.Items.Add(New ComboItem(dr("TMNAME"), dr("CPIN").ToString()))

检索时:

Dim result = DirectCast(cbxTeamMembers.SelectedItem, ComboItem).Value