Subtract Extension method for datatable

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 761
/// <summary>
/// Subtraction of data rows in a datatable
/// </summary>
/// <param name="dt"></param>
/// <param name="insertAt"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static DataTable Subtract(this DataTable dt, int insertAt, string columnName)
{
DataRow dr;
List<object> lstColumnResult = new List<object>();
int res = 0;

//Add the first column name
lstColumnResult.Add(columnName);

for (int i = 1; i < dt.Columns.Count; i++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
if (row == 0)
{
res = res + Convert.ToInt32(dt.Rows[row][i]);
}
else
{
res = res - Convert.ToInt32(dt.Rows[row][i]);
}
}

lstColumnResult.Add(res);
res = 0;
}
//add a new data row
dr = dt.NewRow();
dr.ItemArray = lstColumnResult.ToArray();
//insert the row at the position specified
dt.Rows.InsertAt(dr, insertAt);
//accept the changes
dt.AcceptChanges();
return dt;
}

Comments or Responses

Login to post response