C# 当列名称为动态时,计算列和列的总和并显示在页脚中
我有一个DataTable,它的数据是从数据库中检索的。我试图获得每列每个单元格的值之和,并显示在DataTable的页脚中 但问题是,我检索到的列名是动态的,每次用户提供不同的输入时,它们都会发生变化。当我的列名是动态的时,如何获得每列的总和C# 当列名称为动态时,计算列和列的总和并显示在页脚中,c#,asp.net,datatable,C#,Asp.net,Datatable,我有一个DataTable,它的数据是从数据库中检索的。我试图获得每列每个单元格的值之和,并显示在DataTable的页脚中 但问题是,我检索到的列名是动态的,每次用户提供不同的输入时,它们都会发生变化。当我的列名是动态的时,如何获得每列的总和 protected void search_Click(object sender, EventArgs e) { try { DataTable dt = new DataTable(); string
protected void search_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable();
string from_date = srch_date.Text.ToString();
string to_date = srch_to_date.Text.ToString();
dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);
if (dt != null && dt.Rows.Count > 0)
{
GridView1.DataSource = dt_;
GridView1.DataBind();
}
}
catch (Exception ex) { }
}
您可以循环DataTable中的所有列和行,并在页脚中显示结果
DataTable dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);
//create a array to store the total column values
int[] RowTotals = new int[dt.Columns.Count];
//loop all the rows in the datatable
foreach (DataRow row in dt.Rows)
{
//loop all the columns in the row
for (int i = 0; i < dt.Columns.Count; i++)
{
//add the values for each cell to the total
RowTotals[i] += Convert.ToInt32(row[dt.Columns[i].ColumnName]);
}
}
//loop all the columns again to set the values in the footer
for (int i = 0; i < dt.Columns.Count; i++)
{
GridView1.FooterRow.Cells[i].Text = string.Format("{0:N2}", RowTotals[i]);
}
DataTable dt=new DAL_Reports().Rpt_Count_Transpose(从日期到日期);
//创建一个数组来存储总列值
int[]行总数=新的int[dt.Columns.Count];
//循环数据表中的所有行
foreach(数据行中的数据行)
{
//循环行中的所有列
对于(int i=0;i
假设您知道maximim列号,您可以在GridView的RowDataBound事件中处理它:
在页面类级别声明总计数组:
int maxTotals = 10;
Decimal[] Totals = new Decimal[10];
RowDatBound事件中的进程数据
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.HeaderRow)
{
//Initialize totals array
for (int k=0; k<=maxTotals; k++)
totals[k]=0;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Collect totals from relevant cells
DataRowView rowView = (DataRowView)e.Row.DataItem;
for (int k=0; k<=maxTotals; k++)
totals[k] += (Decimal)rowView[k];
}
if (e.Row.RowType == DataControlRowType.FooterRow)
{
//Show totals
for (int k=0; k<=maxTotals; k++)
e.Row.Cells[k].Text = String.Format("{0:c}",totals[k]);
}
}
受保护的无效GridView1\u行数据绑定(对象发送方,GridViewRowEventArgs e)
{
如果(e.Row.RowType==DataControlRowType.HeaderRow)
{
//初始化总计数组
对于(int k=0;kDon't docatch(Exception ex){}
。这将吞下所有错误,并且您不会知道它们发生了。至少要记录错误。请澄清您想要的是所有单元格的总和还是footer@Nkosi我要每列的总和