Removing Duplicate Records from Dataset/DataTable
Lots of time I found query for removing duplicate record from dataset, so here is the solution provided by Mr. Tony of DotNetSpider. Little bit workout done by me...
Including Duplicate Rows, Datatable looks like
public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}
foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);
return dTable;
}
protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
DataTable dt = ds.Tables["Emp"];
dt = RemoveDuplicateRows(dt, "empname");
GridView1.DataSource = ds.Tables["Emp"].DefaultView;
GridView1.DataBind();
}
foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);
return dTable;
}
protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
DataTable dt = ds.Tables["Emp"];
dt = RemoveDuplicateRows(dt, "empname");
GridView1.DataSource = ds.Tables["Emp"].DefaultView;
GridView1.DataBind();
}
Excluding the duplicate rows from dataset/datatable