Search code examples
c#visual-studioms-accesscomboboxdatareader

Repeated from access database in combobox


Hello everybody this is my first post so I apologize if I made any mistakes.

I have encountered a problem in my code where repeated values are displayed in the combobox dropdown selection. I am trying to display values from a column in my Access database.

Here is my code.

private void Spisak_Load(object sender, EventArgs e)
    {
        OleDbConnection konekcija = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = D:\Programiranje\Programi\Izlozba Pasa\Izlozba Pasa\izlozba.accdb");

        konekcija.Open();

        OleDbCommand komanda = new OleDbCommand("SELECT Sifra, NazivRase FROM Izlozba, Rasa", konekcija);
        OleDbDataReader reader = komanda.ExecuteReader();

        while(reader.Read())
        {
            comboBox1.Items.Add(reader["Sifra"].ToString());
            comboBox2.Items.Add(reader["NazivRase"].ToString());
        }
    }

And here is an image of what the problem looks like: http://imgur.com/b22g3vg


Solution

  • What you are doing here:

    SELECT Sifra, NazivRase FROM Izlozba, Rasa
    

    is a Cross Join, resulting in a cartesian product of both tables. This usually results in duplicate values in the result set.

    There should be an INNER JOIN between the two tables, if you actually need them both.

    SELECT Sifra, NazivRase 
    FROM Izlozba INNER JOIN Rasa
      ON <whatever the matching fields are>
    

    Edit: Oh wait, I just read the rest of the code. The two columns go into two separate dropdown boxes. You need to create two separate SELECT statements for them.