DataTable class in .Net supports the calculation of a column by getting the values from other columns. That means lets say I have a DataTable as dtItems which is having three columns ItemName, Price, Quantity ,if I need to add another column asTotal and the calculated value for this column will be Price* Quantity , this can be done easily without looping through all the rows, it will be automatically calculated during runtime ” dtItems.Columns.Add(“Total“,typeof(int), “Price*Quantity“); “. |
Code: |
DataTable dtItems = new DataTable(); //Add three columns to the DataTable dtItems.Columns.Add("ItemName", typeof(string)); dtItems.Columns.Add("Price", typeof(int)); dtItems.Columns.Add("Quantity", typeof(int)); //Add rows to the DataTable dtItems.Rows.Add("Item1", 100, 1); dtItems.Rows.Add("Item2", 200, 2); dtItems.Rows.Add("Item3", 300, 3); //Add a new Column with the Calculate Value dtItems.Columns.Add("Total", typeof(int), "Price*Quantity"); //Set the DataTable as DataSource of the GridView grdItemsList.DataSource = dtItems;