Friday, February 02, 2007

Removing Duplicate Records from Dataset/DataTable

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

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

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape