| True DBGrid for WinForms Task-Based Help > Displaying a Column Total in the Footer |
You can easily display a sum of all values in a column in the footer of a grid. To do so, you would need to make the column footers visible by setting the ColumnFooters property to True; you would then create a function to calculate the sum of the column. Note that in the following example, the grid has been bound to the Products table in the Northwind database.
Complete the following steps to calculate the total of the UnitsInStock column:
To write code in Visual Basic
| Visual Basic |
Copy Code
|
|---|---|
Public Sub CalculateFooter()
Dim i As Integer
Dim sum As Double
For i = 0 To Me.C1TrueDBGrid1.Splits(0).Rows.Count - 1
sum += Me.C1TrueDBGrid1.Columns("UnitsInStock").CellValue(i)
Next
Me.C1TrueDBGrid1.Columns("UnitsInStock").FooterText = sum
End Sub
|
|
To write code in C#
| C# |
Copy Code
|
|---|---|
public void CalculateFooter()
{
int i = 0;
double sum = 0;
for (i = 0; i <= this.c1TrueDBGrid1.Splits[0].Rows.Count - 1; i++)
{
sum += Convert.ToDouble(this.c1TrueDBGrid1.Columns["UnitsInStock"].CellValue(i));
}
this.c1TrueDBGrid1.Columns["UnitsInStock"].FooterText = Convert.ToString(sum);
}
|
|
To write code in Visual Basic
| Visual Basic |
Copy Code
|
|---|---|
Me.C1TrueDBGrid1.ColumnFooters = True CalculateFooter() |
|
To write code in C#
| C# |
Copy Code
|
|---|---|
c1TrueDBGrid1.ColumnFooters = true; CalculateFooter(); |
|
This code sets the visibility of the column footer and initializes the CalculateFooter function.
The column total for the UnitsInStock column is now displayed in the grid's footer: