Tahi
Tahi

Reputation: 95

ComboBox displays duplicate values

I want to the add the item of ComboBox. I has been successful in adding items but the ComboBox has duplicate items. Why?

This is my code:

Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub

This is the result:

enter image description here

In my table:

enter image description here

Upvotes: 0

Views: 76

Answers (3)

Milind Pawar
Milind Pawar

Reputation: 22

Public Sub load_consigneecode()
    Dim con As OleDbConnection = New OleDbConnection(constring)
    con.Open()
    Dim sql As String = "select con_code from TblConsignee order by con_code"
    Dim cmd As New OleDbCommand(sql, con)
    Dim myreader As OleDbDataReader = cmd.ExecuteReader()

    'add this in code
    cmbCode.Items.Clear();
    While myreader.Read()
        cmbCode.Items.Add(myreader(0).ToString)
    End While

    myreader.Close()
    con.Close()
End Sub

Else use distinct in your SQL query

Upvotes: 1

Bugs
Bugs

Reputation: 4489

You are probably not clearing the items in your ComboBox before adding new ones:

cmbCode.Items.Clear()

That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.

I would also consider implementing Using:

Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

With the changes you code would look something like this:

Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection(constring),
      cmd As New OleDbCommand("SELECT [con_code] FROM [TblConsignee] ORDER BY [con_code]", con)
    con.Open()

    dt.Load(cmd.ExecuteReader())
End Using

cmbCode.DataSource = dt
cmbCode.DisplayMember = "con_code"
cmbCode.ValueMember = "con_code"

Upvotes: 2

Arion
Arion

Reputation: 31239

The first thing I would check is to make sure that you do not added two times

The second thing I would recomened to do it to:

cmbCode.Items.Clear()

in the beginning of the function before adding the items

Upvotes: 1

Related Questions