向datagrid中加横向 纵向的合计 (在datatable中实现,datatable间倒数据)
最终效果
如果实现??
protected System.Web.UI.WebControls.DataGrid DataGrid1;
/// <summary>
/// 数据来源
/// </summary>
DataSet CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("名称", typeof(string)));
dt.Columns.Add(new DataColumn("Value1", typeof(Int32)));
dt.Columns.Add(new DataColumn("Value2", typeof(Int32)));
dt.Columns.Add(new DataColumn("Value3", typeof(Int32)));
dt.Columns.Add(new DataColumn("Value4", typeof(Int32)));
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i.ToString()+"名称";
dr[1] = i;
dr[2] = i+1;
dr[3] = i+2;
dr[4] = i+3;
dt.Rows.Add(dr);
}
DataSet MyData=new DataSet();
MyData.Tables.Add(dt);
return MyData;
}
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
DataSet MyData=CreateDataSource();
// DataGrid1.DataSource= MyData;
// DataGrid1.DataBind();
DataTable MyTable=new DataTable();
DataColumn myColum;
foreach( DataColumn NowDataColumn in MyData.Tables[0].Columns)
{
myColum=new DataColumn();
myColum.DataType=NowDataColumn.DataType;
myColum.ColumnName=NowDataColumn.ColumnName;
MyTable.Columns.Add(myColum);
}
myColum=new DataColumn();
myColum.DataType=System.Type.GetType("System.Int32");
myColum.ColumnName="每行合计";
MyTable.Columns.Add(myColum);
DataRow AcountRow;
int DataColumns=MyData.Tables[0].Columns.Count;
foreach( DataRow NowRow in MyData.Tables[0].Rows)
{
AcountRow=MyTable.NewRow();
AcountRow.ItemArray=NowRow.ItemArray;
//每行合计
GetRowAccount(AcountRow,1,5,DataColumns);
MyTable.Rows.Add(AcountRow);
}
//生成的合计
AcountRow=MyTable.NewRow();
AcountRow[0]="竖列合计";
for(int count=1;count<MyTable.Columns.Count;count++)
foreach (DataRow NowRow in MyTable.Rows)
{
if(!AcountRow.IsNull(count))
{
if (!AcountRow.IsNull(count) )
AcountRow[count]= Convert.ToInt32(AcountRow[count])+Convert.ToInt32(NowRow[count]);
}
else AcountRow[count]=NowRow[count];;
}
MyTable.Rows.Add(AcountRow);
DataGrid1.DataSource=MyTable;
DataGrid1.DataBind();
}
/// <summary>
/// 每行合计
/// </summary>
private void GetRowAccount(DataRow AcountRow,int begincol,int endcol,int accountcol)
{
for(int i=begincol;i<endcol;i++)
{
if(!AcountRow.IsNull(accountcol))
{
if ( !AcountRow.IsNull(i) )
AcountRow[accountcol]= Convert.ToInt32(AcountRow[accountcol])+Convert.ToInt32(AcountRow[i]);
}
else AcountRow[accountcol]=AcountRow[i];
}
}
缺点: 把所有的数据都访问过 肯定效率不是很好