Hello Friends,

Recently i was working on project and my colleague Akhil Patel has asked me that how can we remove duplicate rows from datatable or dataset after binds.

So those who are finding same question here is the answer,

Here is the function which will use to remove duplicate rows from datatable.

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

You have to just pass the datatable and column name of same datatable in which you are thinking that duplicate data would be there.


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 product;", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Product");
DataTable dt = ds.Tables["Product"];
dt = RemoveDuplicateRows(dt, "ProductID");
GridView1.DataSource = ds.Tables["Product"].DefaultView;
GridView1.DataBind();
}

Tags:

This entry was posted on Saturday, July 10th, 2010 at 6:11 am and is filed under .Net Emperor. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a reply

Name (*)
Mail (will not be published) (*)
URI
Comment