2016-05-03 119 views
1

如何刪除C#Windows窗體中的重複標籤頁名稱?我嘗試了很多次,它仍然顯示標籤頁上的重複項目。如何刪除重複的標籤頁?

例子:

Example

我的代碼:

SqlCommand cmd = new SqlCommand("SELECT type FROM Products ORDER BY type ASC", con); 
con.Open(); 
try 
{ 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    DataTable dt = new DataTable(); 
    da.Fill(dt); 
    foreach (DataRow dr in dt.Rows) 
    { 
     tabControl1.TabPages.Add(dr["type"].ToString()); 
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message, "Error"); 
} 
con.Close(); 

回答

3
var cmd = new SqlCommand("SELECT DISTINCT type FROM Products ORDER BY type ASC", con); 
con.Open(); 
try 
{ 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    DataTable dt = new DataTable(); 
    da.Fill(dt); 
    foreach (DataRow dr in dt.Rows) 
    { 
     tabControl1.TabPages.Add(dr["type"].ToString()); 

    } 

} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message, "Error"); 
} 
con.Close(); 
+1

執行它最簡單的方法。 –

+0

多謝:-) – Clement

0

就可以過濾掉重複的行使用此功能

public DataTable RemoveDuplicateRows(DataTable dataTable, string columnName) 
{ 
    Hashtable hashTable = new Hashtable(); 
    ArrayList duplicateList = new ArrayList(); 

    //Add a list of all the unique item values to the hashtable, which in turn stores a combination of key, value pair. 
    //And add duplicate item value in arraylist. 
    foreach (var dataRow in dataTable.Rows) 
    { 
     if (hashTable .Contains(dataRow[columnName])) 
    duplicateList.Add(dataRow); 
    else 
    hTable.Add(dataRow[columnName], string.Empty); 
    } 

    //Removing a list of duplicate items from datatable. 
    foreach (var dRow in duplicateList) 
    dataTable.Rows.Remove(dRow); 

    //Datatable which contains unique records will be return as output. 
    return dataTable; 
} 
+1

事後看來,將sql改爲包含像Sushil Mate這樣的distict可能是解決問題的最簡單,最好的解決方案。 – Sondre

+0

謝謝@sondre。 –