How can I remove duplicate rows from datagridview?
For example:
dataGridView1:
NAMES - LASTNAMES
mary cash
john money
john bucks
jack bank
I want to remove only duplicate names.
After duplicates removed:
NAMES - LASTNAMES
mary cash
john money
jack bank
Loading

Satyapriya NayakRank #47 · 31.5K reputationPosted Aug 6, 2012, 4:26 AM EDT
sathish N28 reputationPosted Aug 6, 2012, 6:34 AM EDT
{
if(!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=Sathish; Initial Catalog=MySampleDB; Integrated Security=true");
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleTable", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds,"UserDetails");
DataTable dt = ds.Tables["UserDetails"];
RemoveDuplicateRows(dt, "UserName"); // Here UserName is Column name of table
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
}
// This method is used to delete duplicate rows of table
public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
foreach (DataRow dtRow in dTable.Rows)
{
if (hTable.Contains(dtRow[colName]))
duplicateList.Add(dtRow);
else
hTable.Add(dtRow[colName], string.Empty);
}
foreach (DataRow dtRow in duplicateList)
dTable.Rows.Remove(dtRow);
return dTable;
}
MetalGearSolid12 reputationPosted Aug 6, 2012, 1:23 PM EDT
Is there any easy/clear code to do this? (Without hash codes) Thanks
sathish N28 reputationPosted Aug 7, 2012, 5:29 AM EDT
===========================
using System.collections;
using System.collections.Generic;