将datagrideview中的多列求和并添加页脚 [英] Sum multi columns in datagrideview and add in footer
问题描述
这些代码与我一起对datagrideview中的一列求和,但我想对datagrideview中的多列求和
these code work with me to sum one column in datagrideview but i want to sum multi columns in datagrideview
decimal sum1 = 0, sum2 = 0;
for (int i = 0; i < dgw.RowCount; i++)
{
// we only sum the first and third column as an example
sum1 += Convert.ToDecimal(dgw.Rows[i].Cells[4].Value);
sum2 += Convert.ToDecimal(dgw.Rows[i].Cells[5].Value);
}
// add the total row
string[] totalrow = new string[] { sum1.ToString(), "", sum2.ToString() };
dgw.Rows.Add(totalrow);
// add a rowheadertitle
dgw.RowHeadersWidth = 60;
dgw.Rows[dgw.RowCount - 1].HeaderCell.Value = "Total";
我尝试过的事情:
这些代码与我一起对datagrideview中的一列求和,但是我想对datagrideview中的多列求和.
What I have tried:
these code work with me to sum one column in datagrideview but i want to sum multi columns in datagrideview
推荐答案
these code work with me to sum one column in datagrideview but i want to sum multi columns in datagrideview
确定吗?
您想对第一列和第三列求和,但要引用Cells[4]
和Cells[5]
Are you sure?
You want to sum the first and third column , but you refer to Cells[4]
and Cells[5]
sum1 += Convert.ToDecimal(dgw.Rows[i].Cells[4].Value);
sum2 += Convert.ToDecimal(dgw.Rows[i].Cells[5].Value);
另外,添加新行的方式是错误的:
Also, the way you add new row is wrong:
string[] totalrow = new string[] { sum1.ToString(), "", sum2.ToString() };
数组的大小必须等于单元数!
例如:
The size of array have to be equal to the count of cells!
For example:
// Set the column header names.
dataGridView1.Columns[0].Name = "Recipe";
dataGridView1.Columns[1].Name = "Category";
dataGridView1.Columns[2].Name = "Main Ingredients";
dataGridView1.Columns[3].Name = "Rating";
// Populate the rows.
//ColNo 0 1 2 3
string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef", "**" };
dataGridView1.Rows.Add(row1);
有关更多详细信息,请参见: DataGridView.行属性(System.Windows.Forms) [
For further details, please see: DataGridView.Rows Property (System.Windows.Forms)[^]
这篇关于将datagrideview中的多列求和并添加页脚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!