0

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";   
        }
    }
2
Contributors
2
Replies
63
Views
3 Years
Discussion Span
Last Post by ddanbe
0

it is not working

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

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.