如何在C#Windows窗体中删除重复的标签页名称?我尝试了很多次,它仍然显示标签页上的重复项目。
示例:
我的代码:
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();
答案 0 :(得分: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)
您可以使用此功能过滤掉重复的行
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;
}