2015-09-27 46 views
0

我正在使用c#在Windows窗體應用程序上工作。我有一個綁定到數據庫的checkListBox。我想知道有沒有辦法從數據庫中刪除任何重複的記錄?如何避免checkListBox中的重複項目

這裏是我的代碼

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); 
    } 
} 
+0

你在哪裏分配清單框? – Sajeetharan

回答

1

第一個答案 - 在查詢中使用DISTINCT

select distinct * from table_1 

另外,我建議你在查詢中指定列名:

select distinct ID, Name from table_1 

但我對錶格中的數據一無所知。

+0

我應該在之前提到過,我的員工姓名是同一個記錄,但他們購買了不同的物品。因此在我的checkListBox中,我有重複的員工。 – RedRocket

+0

@DragonBorn很高興知道。你能接受答案嗎? – Backs