Hi abraham197,
I have created sample code which full-fill your requirement. So please refer the below code.
HTML
<div>
<asp:GridView ID="gvRecords" AutoGenerateColumns="true" runat="server" />
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("CustomerId");
dt.Columns.Add("Name");
dt.Columns.Add("Country");
dt.Rows.Add("1", "Mudassar Khan", "India");
dt.Rows.Add("2", "Maria", "Austria");
dt.Rows.Add("3", "Ana Trujillo", "UK");
dt.Rows.Add("4", "Thomas Hardy ", "Brazil");
dt.Rows.Add("4", "Thomas Hardy ", "Brazil");
dt.Rows.Add("5", "Christina Berglund", "Ireland");
dt.Rows.Add("2", "Maria", "Austria");
DataTable UniqueRecords = RemoveDuplicateRows(dt, "CustomerId");
gvRecords.DataSource = UniqueRecords;
gvRecords.DataBind();
}
}
public DataTable RemoveDuplicateRows(DataTable table, string DistinctColumn)
{
try
{
ArrayList UniqueRecords = new ArrayList();
ArrayList DuplicateRecords = new ArrayList();
foreach (DataRow dRow in table.Rows)
{
if (UniqueRecords.Contains(dRow[DistinctColumn]))
DuplicateRecords.Add(dRow);
else
UniqueRecords.Add(dRow[DistinctColumn]);
}
foreach (DataRow dRow in DuplicateRecords)
{
table.Rows.Remove(dRow);
}
return table;
}
catch (Exception ex)
{
return null;
}
}
Vb.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim dt As New DataTable()
dt.Columns.Add("CustomerId")
dt.Columns.Add("Name")
dt.Columns.Add("Country")
dt.Rows.Add("1", "Mudassar Khan", "India")
dt.Rows.Add("2", "Maria", "Austria")
dt.Rows.Add("3", "Ana Trujillo", "UK")
dt.Rows.Add("4", "Thomas Hardy ", "Brazil")
dt.Rows.Add("4", "Thomas Hardy ", "Brazil")
dt.Rows.Add("5", "Christina Berglund", "Ireland")
dt.Rows.Add("2", "Maria", "Austria")
Dim UniqueRecords As DataTable = RemoveDuplicateRows(dt, "CustomerId")
gvRecords.DataSource = UniqueRecords
gvRecords.DataBind()
End If
End Sub
Public Function RemoveDuplicateRows(table As DataTable, DistinctColumn As String) As DataTable
Try
Dim UniqueRecords As New ArrayList()
Dim DuplicateRecords As New ArrayList()
For Each dRow As DataRow In table.Rows
If UniqueRecords.Contains(dRow(DistinctColumn)) Then
DuplicateRecords.Add(dRow)
Else
UniqueRecords.Add(dRow(DistinctColumn))
End If
Next
For Each dRow As DataRow In DuplicateRecords
table.Rows.Remove(dRow)
Next
Return table
Catch ex As Exception
Return Nothing
End Try
End Function
Output
CustomerId | Name | Country |
1 |
Mudassar Khan |
India |
2 |
Maria |
Austria |
3 |
Ana Trujillo |
UK |
4 |
Thomas Hardy |
Brazil |
5 |
Christina Berglund |
Ireland |