Remove duplicate records from a table

Posted by Naveenmanam under ASP.NET category on | Views : 4371
Remove duplicate records from a table

This code sample shows how to identify and remove duplicate records from a dataset/datatable.

Following Code will take inputs datatable and column name wherein we need to find duplicates items and remove.

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();

//Add list of all the unique item value to hashtable, which stores combination of key, value pair.

foreach (DataRow drow in dTable.Rows)
if (hTable.Contains(drow[colName]))
hTable.Add(drow[colName], string.Empty);

//Removing a list of duplicate items from datatable.
foreach (DataRow dRow in duplicateList)

//Datatable which contains unique records will be return as output.
return dTable;

Example showing how to use above method:

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

// Filling a employee table
DataTable dt = ds.Tables["Emp"];
dt = RemoveDuplicateRows(dt, "empname");

GridView1.DataSource = ds.Tables["Emp"].DefaultView;

Comments or Responses

Posted by: Naveenmanam on: 5/4/2010 Level:Starter | Status: [Member]
how it is..?
tell me

Login to post response