I did it as follows (only works when you use a binding data source)
Create a custom datagridview control and inherit datagridview
public partial class MyGridView : DataGridView
Declare the class that contains the column name, the final value, and the format that will be displayed
[Serializable] public class SummaryDataProperty { public string ColumnName { get; set; } public string Format { get; set; } internal decimal Value { get; set; } }
Declare a list of summary properties in MyDataGridView
public List<SummaryDataProperty> SummaryDataPropertyNames { get; set; }
After the data binding is complete, calculate the summary and display it in the column heading.
protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e) { base.OnDataBindingComplete(e); if (SummaryDataPropertyNames.Count > 0) { if (DataSource is BindingSource) { var ds = (DataSource as BindingSource); foreach (var prop in SummaryDataPropertyNames) { prop.Value = 0; var col = this.Columns[prop.ColumnName]; foreach (var l in ds.List) { decimal val; if (decimal.TryParse(Convert.ToString(l.GetType().GetProperty(col.DataPropertyName).GetValue(l, null)), out val)) prop.Value += val; } col.HeaderText = col.HeaderText.Split('[')[0].TrimEnd(' ') + " [" + prop.Value.ToString(prop.Format) + "]"; } } } }
Since the binding data source gives a list of objects from the data source. It is easy to iterate through a list of binding sources. I do not know how to do this with an object data source or BindingDatasource.Current. I'm still looking for a solution.
source share