如何将数据库列中的值添加到ComboBox而不重复?

时间:2015-12-07 05:43:10

标签: sql-server combobox vb.net-2010

我在数据库中有一个列,其中包含Good,Bad和May Be等值。有200行,其中20行有Value Good,50有Bad等等,我可以将数据库中的值加载到comboBox但是每个值(200)都显示在组合框中,如何避免重复。我添加了我使用的代码。

导入System.Data.SqlClient

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    'CREATE OBJECT CONNECTION
    Dim cn As New SqlConnection

    With cn
        .ConnectionString = "server=(local)\sqlexpress;database=trial;integrated security=true"
        .Open()
    End With

    'CREATE OBJECT DATA TABLE AND DATA ADAPTER
    Dim dt As New DataTable
    Dim da As New SqlDataAdapter("select kode,nama from warna order by kode", cn)

    da.Fill(dt)
    If dt.Rows.Count > 0 Then
        With ComboBox1
            .Items.Clear() 'CLEAR ITEMS COMBOBOX
            For i As Integer = 0 To dt.Rows.Count - 1
                'ADD ITEMS TO COMBOBOX
                .Items.Add(dt.Rows(i).Item("kode") & " - " & dt.Rows(i).Item("nama"))
            Next
            'CLEAR TEXT COMBOBOX
            .Text = Nothing
            .SelectedIndex = -1
        End With
    End If

    'CLEAR ALL OBJECT AND MEMORY
    With cn
        .Close()
        .Dispose()
    End With
    cn = Nothing
    dt.Dispose()
    dt = Nothing
    da.Dispose()
    da = Nothing

End Sub

结束班

1 个答案:

答案 0 :(得分:0)

在SQLAdapter中填充数据时使用DISTINCT关键字:

select distinct kode,nama from warna order by kode

您可以在Kode和nama组合中的DB中使用重复项时使用。