Monday, 19 June 2017

How to merge rows in a DataTable when data in multiple columns match using C#.

How to merge rows in a DataTable when data in multiple columns match using C#.
Description:
In this example we explain that how to merging multiple DataTables into single Datatable in Asp.Net using C#.or how to merge rows in a DataTable when data in multiple columns match. Or how to merge rows data from DataTable in C#.or how to sum Cell Values based on same column (with Same Number or Id) in Grid View.

Here we demonstrate how to merge two different rows of DataTable into single rows in same DataTable using C#.or how to merge rows in a DataTable when data in multiple columns match. Or merge rows of the same DataTable with sum of columns in single rows and bind to GridView in asp.net using C#.

Code:

DataTable dtemployee = dtOriginal.Clone();
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
    bool isDupe = false;
    for (int j = 0; j < dtemployee.Rows.Count; j++)
    {
        if (dtOriginal.Rows[i][0].ToString() == dtemployee.Rows[j][0].ToString()
            && dtOriginal.Rows[i][1].ToString() == dtemployee.Rows[j][1].ToString()
            && dtOriginal.Rows[i][2].ToString() == dtemployee.Rows[j][2].ToString())
        {
            dtemployee.Rows[j][3] = int.Parse(dtemployee.Rows[j][3].ToString()) + int.Parse(dtOriginal.Rows[i][3].ToString()); 
            isDupe = true;
            break;
        }
    }
 
    if (!isDupe)
    {
        dtemployee.ImportRow(dtOriginal.Rows[i]);
    }
}


0 comments:

Post a Comment