Below is the code to remove duplicate rows from DataTable using C#. To use this function call in the which ever event you want like this.
private void btnRemove_Click(object sender, EventArgs e)
{
List<string> keyColumns = new List<string>();
keyColumns.Add("ColumnName1");
keyColumns.Add("ColumnName2");
keyColumns.Add("ColumnName3");
RemoveDuplicates(ref dtAlarmData, keyColumns);
}
//Method to remove Duplicate value from DataTable
public
static void RemoveDuplicatesFromDataTable(ref DataTable table, List<string> keyColumns)
{
Dictionary<string, string> uniquenessDict = new Dictionary<string, string>(table.Rows.Count);
StringBuilder stringBuilder = null;
int rowIndex = 0;
DataRow row;
DataRowCollection rows = table.Rows;
while (rowIndex < rows.Count - 1)
{
row = rows[rowIndex];
stringBuilder = new StringBuilder();
foreach (string colname in keyColumns)
{
stringBuilder.Append(((string)row[colname]));
}
if (uniquenessDict.ContainsKey(stringBuilder.ToString()))
{
rows.Remove(row);
}
else
{
uniquenessDict.Add(stringBuilder.ToString(), string.Empty);
rowIndex++;
}
}
}