HaresH Chaudhari

Freelance Web Developer

Remove duplicate rows from dataset or datatable in Asp.Net

Hello friend have take look on below code which might useful for you to remove any duplicate rows from your dataset or data table in asp.net with C#.
The first methods return the datatabe which removed duplicate row from your dataset. You cahve to fill your dataset and then in temporary table you can store new returned datatable and store in dataset.

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 btnRemoveDuplicate_Click(object sender, EventArgs e)
{
Fill your dataset
string strConn = ConfigurationManager.ConnectionStrings["Your Connection String key from config file"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter(“select * from Test”, conn);
DataSet ds = new DataSet();
da.Fill(ds, “Test”);

Take Temporary table and store 0th position’s table from dataset in your temp table.
DataTable dt = ds.Tables["Test"];

Pass that temp table in above method, so it return fresh table with duplicating rows. You must have to define the columnname for which you are going to remove duplicate rows. Here in example, “Name” column is passed for duplicate wors removal.
dt = RemoveDuplicateRows(dt, “Name”);

You have fresh table with distinct records here in dt table, you can assign in dataset of bing to your any data control
dgTest.DataSource = ds.Tables["Test"].DefaultView;
dgTest.DataBind();
}

I hope it helpful for you.
Thanks

Advertisement

Filed under: 1, ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.