0

Hi all I am binding a DataTable to the DataGridView with some of the columns along with some amount fields.

I need to show the sum of the columns for each of the amount filed in DataGridView. I have already searched for many options to add a footer to the DataGridView. Is there any possibility to sum up few columns in the DataTable so that I can display the data in DataGridView?

This is my datatable data roughly:

  Name  Address   Amount   DiscountAmount
   XYZ   ABC       100.00         20.00
   ABC   DEF       150.00         0.00

Required result is:

  Name  Address   Amount   DiscountAmount
   XYZ   ABC       100.00         20.00
   ABC   DEF       150.00         0.00
                   250.00         20.00

I have already tried some thing like following - and it didn't worked:

DataRow lRow = lDTGrid.NewRow();
lRow[0] = "Totals";
for (int i = 1; i < lDTGrid.Columns.Count; i++)
{
  lRow[lDTGrid.Columns[i].ColumnName] = lDTGrid.Compute("Sum(" + lDTGrid.Columns[i].ColumnName + ")", "");
}
Andrii Kalytiiuk
  • 1,501
  • 14
  • 26
Developer
  • 8,390
  • 41
  • 129
  • 238
  • Any reason why you're not using [foreach](http://msdn.microsoft.com/en-us/library/aa288257%28v=vs.71%29.aspx)? This won't solve the problem, but it should make the code simpler. – beatgammit Jul 13 '13 at 17:21

2 Answers2

0

Have you tried using the DataTable.Compute() method

private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable. 
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}
Rwiti
  • 1,056
  • 1
  • 13
  • 31
0

Does it have to be row in datagridview? Can't you use textboxes under datagridview? Much easier and still neat.

You can make them unabled, and put there a sum from column at one of events (cell edit, row added or something simillar).

Łukasz Motyczka
  • 1,169
  • 2
  • 13
  • 35