【问题标题】:Sum the rows in Gridview对 Gridview 中的行求和
【发布时间】:2014-08-12 17:10:18
【问题描述】:

我想总结 gridview 中的两列并在标签中显示总数。我在 gridview 中启用了分页。

使用此代码,我将两列的总数相加,但是,总数仅适用于所选页面。

如何进行总计来汇总所有页面中选定列的所有行?

    decimal priceTotal = 0;
    int totalMinutes = 0;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total"));
            totalMinutes += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Duration"));
        }
        lblTotalPrice.Text = "Total Cost: $"+ priceTotal.ToString();
        lblTotalMinutes.Text = "Total duration: " + totalMinutes.ToString();
    }

【问题讨论】:

  • 我有,但我只是不想调用另一个查询或过程来返回总和,因为我知道我可以遍历 gridview。

标签: c# asp.net gridview


【解决方案1】:
decimal price = 0;
foreach (DataGridViewRow row in DataGridView.Rows)
{
     price += row.Cells["Total"]!=null ? Convert.ToDecimal(row.Cells["Total"].Value) : 0;
}

lblTotalPrice.Text = "Total Cost: $"+ price.ToString("n2");

【讨论】:

  • 我收到以下错误The name DataGridview does not exist in the current context
  • 我有,但我得到不同的错误The type or namespace name DataGridViewRow could not be found...
  • 我也试过了。不喜欢row.Cells["Total"] overload
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 2015-06-20
  • 2011-03-06
  • 2015-06-16
  • 2021-02-20
  • 2019-04-11
相关资源
最近更新 更多