当列名称是动态时,计算列的总和并在页脚中显示

时间:2017-07-08 11:06:17

标签: c# asp.net datatable

我有一个DataTable,其数据是从数据库中检索的。我试图逐列获得每个单元格的值的总和,并显示在DataTable的页脚中。

但问题是,我检索到的列名是动态的,每次用户提供不同的输入时它们都会有所不同。当我的列名称是动态的时候,如何获得每列的总和。

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) { }
}

2 个答案:

答案 0 :(得分:2)

您可以循环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]);
}

答案 1 :(得分:0)

假设您知道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]);
  }
}

如果您不知道列的最大数量,您可以始终在for循环中放置try / catch并在出现ArrayOutOfBoundException的情况下退出循环

相关问题