日期:2014-05-20  浏览次数:20882 次

c#(WinForm)如何让DataGridView在最后一行增加合计功能?
c#(WinForm)如何让DataGridView在最后一行增加合计功能?

------解决方案--------------------
帮顶
------解决方案--------------------
自己编辑datatable,然后在最下面加个行,自己计算后把合计值放进去,绑定就显示了
------解决方案--------------------
许算Dataset然后在DataSet里新new一行出来,再绑定到DataGridView就OK了。
------解决方案--------------------
给你一个参考:

http://community.csdn.net/Expert/topic/5261/5261296.xml?temp=.4389002

这个帖子跟你的需求是一样的。
------解决方案--------------------
给你一个统计部件的例子

DataTable table=new DataTable();

DataColumnCollection c=table.Columns;
c.Add( "序号 ",typeof(String));
c.Add( "部件名称 ",typeof(String));
c.Add( "部件规格 ",typeof(String));
c.Add( "单位 ",typeof(String));
c.Add( "单价 ",typeof(System.String));
c.Add( "库存数量 ",typeof(String));
c.Add( "总金额 ",typeof(String));



DataRow row4=table.NewRow();
row4[0]= "序号 ";
row4[1]= "部件名称 ";
row4[2]= "部件规格 ";
row4[3]= "单位 ";
row4[4]= "单价 ";
row4[5]= "库存数量 ";
row4[6]= "总金额 ";
table.Rows.Add(row4);

DataRow row2=table.NewRow();
decimal sum=0;

for(int i=1;i <=s.Tables[0].Rows.Count;i++)
{
DataRow row=table.NewRow();
for(int j=1;j <7;j++)
{
row[0]=i;
row[j]=s.Tables[0].Rows[i-1][j-1];


}
table.Rows.Add(row);
}
for(int k=1;k <=s.Tables[0].Rows.Count;k++)
{
sum=sum+decimal.Parse(table.Rows[k][6].ToString());

}

row2[0]= "合计 ";
row2[1]= " ";
row2[2]= " ";
row2[3]= " ";
row2[4]= " ";
row2[5]= " ";
row2[6]=sum.ToString();
table.Rows.Add(row2);
return table;

------解决方案--------------------
你可以使用DataColumn的Expression,例如
DataTable tb=new DataTable();
DataColumn c_0 = new DataColumn();
c_0.DataType = GetType( "int ");
c_0.ColumnName = "C_0 ";

DataColumn c_1 = new DataColumn();
c_1.DataType = GetType( "int ");
c_1.ColumnName = "C_1 ";


DataColumn c_2 = new DataColumn();
c_2.DataType = GetType( "int ")
c_2.ColumnName = "C_2 ";
C_2.Expression = "C_0 + C_1 ";

tb.Columns.Add(C_0);
tb.Columns.Add(C_1);
tb.Columns.Add(C_2);



------解决方案--------------------
顶.. 不同的需要不同的方法.但是同一个目标----最高性能的实现目的!
------解决方案--------------------
int rowCount = dataGridView1.Rows.Count;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
int sum = 0;
for (int j = 0; j < rowCount - 1; j++)
{
sum += int.Parse((string)dataGridView1.Rows[j].Cells[i].Value);
}
dataGridView1.Rows[rowCount - 1].Cells[i].Value = sum;
}
------解决方案--------------------