Add a row with totals to a DataGridView

ddanbe 0 Tallied Votes 2K Views Share

Well, start a new forms application from VS.
In design mode, drop a DataGridView and a Button on the form and fill in the code.
The button clickhandler will add an extra totals row to the datagrid.
Here it will keep adding and totaling, which is of course meaningless, but it's just example code.
Enjoy.

public Form1()
        {
            InitializeComponent();

            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Col 1";
            dataGridView1.Columns[0].Width = 80;
            dataGridView1.Columns[1].Name = "Col 2";
            dataGridView1.Columns[1].Width = 80;
            dataGridView1.Columns[2].Name = "Col 3";
            dataGridView1.Columns[2].Width = 80;

            dataGridView1.AllowUserToAddRows = false; //removes "extra" row
            dataGridView1.RowHeadersDefaultCellStyle.Padding = new Padding(3);//helps to get rid of the selection triangle

            // add 3 rows with values
            string[] row = new string[] { "1", "2", "3" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "2", "2", "4" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "3", "3", "7" };
            dataGridView1.Rows.Add(row);
        }

        private void TotalColumnsBtn(object sender, EventArgs e)
        {
            int sum1 = 0, sum2 = 0;
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                // we only sum the first and third column as an example
                sum1 += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value);
                sum2 += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
            }
            // add the total row
            string[] totalrow = new string[] { sum1.ToString(), "", sum2.ToString() };
            dataGridView1.Rows.Add(totalrow);
            // add a rowheadertitle
            dataGridView1.RowHeadersWidth = 60;
            dataGridView1.Rows[dataGridView1.RowCount - 1].HeaderCell.Value = "Total";   
        }
    }
Afzaal291 0 Newbie Poster

it is not working when u bound data from any table...

ddanbe 2,724 Professional Procrastinator Featured Poster

it is not working

That is always a possibility.
May I also know what exactly is not working?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.