RedRocket
RedRocket

Reputation: 1733

How can I avoid duplicate items in a checkListBox

I am working on my windows form application using c#. I have a checkListBox that is binded to db. I am wondering is there a way to delete any duplicate record from the database?

Here is my code

 private void fill_checkListBox()
 {
     try
     {
         string query = "select * from table_1 ";

         SqlCommand myTeacherCommand = new SqlCommand(query, myConn);

         //reading the value from the query
         dr = myCommand.ExecuteReader();
         //Reading all the value one by one
         teacherCB.Items.Clear();


         while (dr.Read())
         {
             string name = dr.IsDBNull(2) ? string.Empty : dr.GetString(2);

             teacherCB.Items.Add(name);

             if (!checkBox.Items.Contains(name))
             {
                  teacherCB.Items.Add(name);
             }           
         }
         dr.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }

Upvotes: 0

Views: 76

Answers (1)

Backs
Backs

Reputation: 24913

The first answer - use DISTINCT in query:

select distinct * from table_1

Also, I advice you to specify column names in query:

select distinct ID, Name from table_1

But I don't know anything about your data in table.

Upvotes: 1

Related Questions