How to generate a sum of a particular column in DataGridView with C#?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sean Len
    New Member
    • Oct 2010
    • 13

    How to generate a sum of a particular column in DataGridView with C#?

    Hi guys, currently Im working on a program where generate a datagridview from database.
    After generating the datagridview, i would like to add another row below the column to sum the value.

    Example:
    Original DataGridView
    ----------------------
    |ID | Name | Value |
    ----------------------
    | 1| User1| 2000|
    | 2| User2| 1500|
    | 3| User3| 500|
    ----------------------

    Then I would like to add another row to display to sum:
    ----------------------
    |ID | Name | Value |
    ----------------------
    | 1| User1| 2000|
    | 2| User2| 1500|
    | 3| User3| 500|
    | | | 4000|
    ----------------------

    How should I targeting the "Value" Column?
    I perform alot of research online and I manage to get generate all column with Int32 Data Type.
    Code:
    public Form1()
            {
                InitializeComponent();
                this.dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
            }
            void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
            {
                int sum = 0;
                // only draw the cells of the extra row by ourselves, leaving the rest cells to the system
                if (e.RowIndex == this.dataGridView1.NewRowIndex && e.ColumnIndex > -1)
                {
                    for (int i = 0; i < this.dataGridView1.NewRowIndex; i++)
                    {
                        if (this.dataGridView1.Rows[i].Cells[e.ColumnIndex].Value.ToString().Trim() != "" &&
                            this.dataGridView1.Rows[i].Cells[e.ColumnIndex].ValueType.Name == "Int32")
                        {
                            sum += (int)this.dataGridView1.Rows[i].Cells[e.ColumnIndex].Value;
                        }
                    }
                    e.PaintBackground(e.CellBounds, false);
                    e.Graphics.DrawString(sum.ToString(), this.dataGridView1.Font, Brushes.Black, e.CellBounds.Left + 2, e.CellBounds.Top + 2);
    
                    e.Handled = true;
                }
            }
    But when I try to target only 1 particualr column it give me error.

    Anyone could help me with this?

    Thanks!
  • Sfreak
    New Member
    • Mar 2010
    • 64

    #2
    You can perform a loop like:

    Code:
    int sum = 0;
    for (int x = 0; x < dataGridView1.Rows.Count; x++ )
    {
      sum += Convert.ToInt32(dataGridView1.Rows[x].Cells["Column"].Value);
    }

    Comment

    Working...