【问题标题】:Getting sum of gridview cloumn using for loop使用for循环获取gridview列的总和
【发布时间】:2016-05-11 22:06:38
【问题描述】:

我正在尝试使用 for 循环获取网格视图列的总和并将其放入标签中

我尝试了下面的代码,但结果不正确

decimal total = 0;
protected void gridpandl_RowDataBound(object sender, GridViewRowEventArgs e)
{
    for (int index = 0; index < this.gridpandl.Rows.Count; index++)
    {
        string proid = gridpandl.DataKeys[index].Value.ToString();
        string Purchase = GetPurchase(proid);
        this.gridpandl.Rows[index].Cells[2].Text = Purchase;
        total += Convert.ToDecimal(Purchase);
        lbltotal.Text = Convert.ToString(total);

    }
}

【问题讨论】:

  • 也许我错了,但这个事件被称为 foreach 行。因此,如果您有两行价值为 10 的购买,您最终会得到总共 40。我认为您应该在 DataBind() 调用之后移动循环,而不是在 RowDataBoud 事件中
  • 谢谢你是对的

标签: c# asp.net .net gridview


【解决方案1】:

RowDataBound 事件被称为 foreach row。因此,如果您有两行值为 10,您将被调用两次。第一次总数是正确的,但第二次它不断增加总数,最终得到 40。

你应该在 DataBind() 之后移动你的循环,像这样......

this.gridpandl.DataSource = ... your get data source routine....
this.gridpandl.DataBind();
lbltotal.Text = SumRows();

....

private decimal SumRows()
{
    decimal total = 0;
    for (int index = 0; index < this.gridpandl.Rows.Count; index++)
        total += Convert.ToDecimal(this.gridpandl.Rows[index].Cells[2].Text);
    return total
}
protected void gridpandl_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string proid = gridpandl.DataKeys[index].Value.ToString();
    this.gridpandl.Rows[index].Cells[2].Text = GetPurchase(proid);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2021-12-17
    • 1970-01-01
    • 2022-01-08
    • 2013-05-08
    • 2015-12-22
    相关资源
    最近更新 更多