Good day,
How can I add a total/sub total for each numeric column in datagridview?
Thanks.
Hi Glenn,
If your DataGridView is unbound: one way you can accomplish this is to programmatically add a new row to the bottom:
var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
If your DataGridView is bound you can use a DataTable:
DataTable dt = myDataGridView.DataSource as DataTable;
//Create the new row
DataRow row = dt.NewRow();
//Populate the row with data
//Add the row to data table
dt.Rows.Add(row);
To calculate the totals of the columns:
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.Text = sum.ToString();
Some useful links:
Calculating Sum of Column: https://stackoverflow.com/questions/3779729/how-i-can-show-the-sum-of-in-a-datagridview-column
Adding Row to DataGridView Programmatically: https://stackoverflow.com/questions/10063770/how-to-add-a-new-row-to-datagridview-programmatically
DataBound DGV Row Adding: https://stackoverflow.com/questions/18125147/how-to-programmatically-add-a-row-to-a-datagridview-when-it-is-data-bound
I hope this helps! Let me know if you have any questions about it!
Best regards,
Levie
Frozen rows aren’t available yet, but they will be sometime in the future!
You can add a second datagridview on top of the first one and dock it to the bottom. The datagridview will automatically adjust and make space for it. You can then add events to the column width changed events to keep them in sync.
The following code will help you calculate the total of the visible cells (You can modify to get certain column):
public void GetVisibleCells(DataGridView dgv)
{
var visibleRowsCount = dgv.DisplayedRowCount(true);
var firstDisplayedRowIndex = dgv.FirstDisplayedCell.RowIndex;
var lastvisibleRowIndex = (firstDisplayedRowIndex + visibleRowsCount) - 1;
for (int rowIndex = firstDisplayedRowIndex; rowIndex <= lastvisibleRowIndex; rowIndex++)
{
var cells = dgv.Rows[rowIndex].Cells;
foreach (DataGridViewCell cell in cells)
{
if (cell.Displayed)
{
// This cell is visible...
// Your code goes here...
}
}
}
}
I hope this helps! Let me know,
Best regards,
Levie
Please login first to submit.