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
sathish NPosted Aug 7, 2012, 9:29 AM
===========================
using System.collections;
using System.collections.Generic;
MetalGearSolidPosted Aug 6, 2012, 5:23 PM
Is there any easy/clear code to do this? (Without hash codes) Thanks
sathish NPosted Aug 6, 2012, 10:34 AM
{
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;
}
Satyapriya NayakPosted Aug 6, 2012, 8:26 AM