You could create a new class that derives from DataGridView and and the custom implementation. I have knocked up the example below. This will total up the named column and raise an event with the new sum which contain the value. The value is also available from a public property.
You would probably want to improve on this though, e.g. read only property for the sum, better error handling etc. etc. This is only a rough proto!
(I think it would be better to do this totalisation outwith the DGV, and handle its events to do the calc yourself from your form etc. and leave the DGV as standard)
Here is the CLASS for the new custom datagridview
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class CustomDataGridView : DataGridView
{
public Boolean EnableColumnSumming { get; set; }
public String ColumnNameToSum { get; set; }
public Double ColumnSum { get; set; }
public delegate void ColumnSumChangedHandler(object o, ColumnSumChangedEventArgs e);
public event ColumnSumChangedHandler ColumnSumChanged;
public class ColumnSumChangedEventArgs : EventArgs
{
public readonly double TheSum;
public ColumnSumChangedEventArgs(double sum)
{
TheSum = sum;
}
}
protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
{
base.OnCellValueChanged(e);
doCellSumming();
}
private void doCellSumming()
{
if (EnableColumnSumming && base.Columns.Contains(ColumnNameToSum))
{
Double total = 0;
foreach (DataGridViewRow row in base.Rows)
{
double value = 0;
try
{
value = Double.Parse(row.Cells[ColumnNameToSum].FormattedValue.ToString());
}
catch (Exception)
{
value = 0;
}
total = total + value;
}
ColumnSum = total;
ColumnSumChanged(this,new ColumnSumChangedEventArgs(ColumnSum));
}
else
{
ColumnSum = 0;
ColumnSumChanged(this, new ColumnSumChangedEventArgs(ColumnSum));
}
}
}
}
On a empty windows form app you could then do the following;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
CustomDataGridView dgv = new CustomDataGridView();
Label label1 = new Label();
public Form1()
{
InitializeComponent();
dgv.Top = 10;
dgv.Left = 10;
dgv.Height = 250;
dgv.Width = 250;
dgv.ColumnHeadersVisible = true;
dgv.ColumnCount = 2;
dgv.Columns[0].Name = "Name";
dgv.Columns[1].Name = "Amount";
dgv.ColumnNameToSum = "Amount";
dgv.EnableColumnSumming = true;
Controls.Add(dgv);
label1.Top = 10;
label1.Left = 270;
label1.Width = 50;
label1.Text = "0";
Controls.Add(label1);
dgv.ColumnSumChanged += new CustomDataGridView.ColumnSumChangedHandler(dgv_ColumnSumChanged);
}
void dgv_ColumnSumChanged(object o, CustomDataGridView.ColumnSumChangedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("The New Column Sum is:" + e.TheSum.ToString());
label1.Text = e.TheSum.ToString();
}
}
}