如何从访问数据库列中获取每个唯一值并添加到组合框项目

时间:2014-12-18 03:20:12

标签: database combobox ms-access-2007

我不专业,但我正在努力学习VB.net。我正在制作一个项目,我想要从访问数据库中的列中获取每个唯一值并将其添加到我的组合框中。任何人都可以帮助我吗?

Private Sub showItems()

    Dim comm As OleDbCommand
    Dim commStr As String = "SELECT Item_Name FROM Add_Items WHERE (Item_Name <> '"
    Dim RD As OleDbDataReader

    conn = New OleDbConnection(connStr)
    conn.Open()

    If cbItemname.Items.Count = 0 Then
        comm = New OleDbCommand("Select Item_Name from Add_Items", conn)
        RD = comm.ExecuteReader
        While RD.Read
            cbItemname.Items.Add(RD.GetString(0))
        End While
    End If


    For Each i As Object In cbItemname.Items
        comm = New OleDbCommand(commStr & i & "')", conn)
        RD = comm.ExecuteReader
        While RD.Read
            cbItemname.Items.Add(RD.GetString(0))
            Exit While
        End While
    Next

    conn.Close()

    End Sub

2 个答案:

答案 0 :(得分:1)

comm = New OleDbCommand("Select DISTINCT Item_Name from Add_Items", conn)

http://office.microsoft.com/en-in/access-help/HV080760568.aspx

您可能会收到此错误,因为您的数据库表名称不正确。确保您位于“表”选项卡中并检查表的名称。 DISTINCT和UNIQUE(对于MySQL)是正确的解决方案。

答案 1 :(得分:0)

我按照vipul给出的指示。它运作良好,我为品牌和模型制作了一些私人潜艇,它突然停止工作。现在,当我的表单从上一个父表单加载时,它会挂起。

 Private Sub showItems()

    Dim comm As OleDbCommand
    Dim commStr As String = "SELECT DISTINCT Item_Name from Add_Items"
    Dim ReadData As OleDbDataReader

    itemnamecombo.Items.Clear()
    ItemChkboxList.Items.Clear()

    Try
        conn = New OleDbConnection(ConnStr)
        conn.Open()
        comm = New OleDbCommand(commStr, conn)
        ReadData = comm.ExecuteReader

        While ReadData.Read
            itemnamecombo.Items.Add(ReadData.GetString(0))
            ItemChkboxList.Items.Add(ReadData.GetString(0))

        End While

    Catch ex As Exception
        'MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()
    End Try
    If itemnamecombo.Items.Count <> 0 Then
        itemnamecombo.SelectedIndex = 0
    End If

End Sub