0

Greetings i am facing this problem where i need to remove any duplicates that are being populated from mysql database into the combobox.

this is my code:

void fillcatagory()
    {
        string query = "select * from CatagorieTable";
        MySqlCommand cmd = new MySqlCommand(query, Con);
        MySqlDataReader rdr;
        try
        {
            Con.Open();
            DataTable dt = new DataTable();
            dt.Columns.Add("Catagname", typeof(string));
            rdr = cmd.ExecuteReader();
            dt.Load(rdr);
            catcombo.ValueMember = "Catagname";
            catcombo.DataSource = dt;
            searchcombo.ValueMember = "Catagname";
            searchcombo.DataSource = dt;
            Con.Close();
        }
        catch
        {

        }
    }
  • You essentially want to remove duplicates from the DataTable. It has been answered before: https://stackoverflow.com/questions/4415519/best-way-to-remove-duplicate-entries-from-a-data-table – Velvel Jan 29 '22 at 02:05
  • 1
    Use `select distinct` – CodingYoshi Jan 29 '22 at 02:11
  • I may be missing something, but I do not see how any items would be added to the combo boxes. At least not with the posted code. The code “adds” a column to a `DataTable` … `dt.Columns.Add("Catagname", typeof(string));` … then … the code fills that table with data from the DB. Then that table is used as a data source to the combo boxes. Appearing “odd” to me is that the rows in the “Catagname” column will be “empty.” … ? … – JohnG Jan 29 '22 at 03:51
  • In addition, using the “same” data source for BOTH combo boxes is odd. If the user changes one combo box… then the other combo box will change to the same value. In other words, both combo boxes will ALWAYS contain the same value. … ? … – JohnG Jan 29 '22 at 03:51
  • Replying to @JohnG greetings mr john this isnt my main code which i will be using distinct in I will use it in the (PO number) column which is basically a unique number that is attached to items purchased for a company and each item will be added to a row of its own (with its po) and i want the user to search for any po that he wants without the need of typing it (thats why duplicates are a problem for me) – Omar Fayoumi Jan 30 '22 at 17:37

1 Answers1

0

Update your query to return unique category names like so:

string query = "select distinct Catagname from CatagorieTable";

Since you're only using the one column, there's no reason to select anything else.

John Glenn
  • 1,469
  • 8
  • 13