Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i want to create a custom datagridview in c# that have a custom property that shows the sum of the specific column , how can i do that?
Posted

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
C#
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;

        //Event Handler Event Args
        public class ColumnSumChangedEventArgs : EventArgs
        {
            public readonly double TheSum;

            public ColumnSumChangedEventArgs(double sum)
            {
                TheSum = sum;
            }
        }

        //Use the base class Cell Changed to Trigger a Column calculation
        protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
        {
            base.OnCellValueChanged(e);
            doCellSumming();
        }

        private void doCellSumming()
        {
            //Check summing enabled and Column Name actually Exists
            if (EnableColumnSumming && base.Columns.Contains(ColumnNameToSum))
            {
                Double total = 0;
                foreach (DataGridViewRow row in base.Rows)
                {
                    double value = 0;
                    try
                    {
                        //Try and convert the cell value to a double
                        value = Double.Parse(row.Cells[ColumnNameToSum].FormattedValue.ToString());
                    }
                    catch (Exception)
                    {
                        //Unable to convert cell, invalid type so set cell value to 0;
                        value = 0;

                    }
                    total = total + value;
                }
                //update the column total
                ColumnSum = total;
                //Raise the ColumnSum Changed Event
                ColumnSumChanged(this,new ColumnSumChangedEventArgs(ColumnSum));

            }
            else
            {
                //No valid cells or summing disabled
                ColumnSum = 0;
                ColumnSumChanged(this, new ColumnSumChangedEventArgs(ColumnSum));
            }
        }

    }
}



On a empty windows form app you could then do the following;
C#
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);

            //Label to Show column sum
            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();
            
        }
    }
}
 
Share this answer
 
Comments
a.bolandnataj106 16-Oct-11 1:37am    
Thank you very much ,that's great
1. Create a UserControl that inherits from DataGridView
C#
public partial class DataGridViewWithSum : DataGridView
{
}

2. Add the desired function to your newly created UserControl
C#
public partial class DataGridViewWithSum : DataGridView
{
     public decimal SumOf ( string column_name )
     {
          // add code to sum values in specified column
     }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900