使用for循环获得gridview cloumn的总和

时间:2016-05-11 22:06:39

标签: c# asp.net .net gridview

我正在尝试使用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);

    }
}

1 个答案:

答案 0 :(得分:1)

RowDataBound事件称为foreach行。因此,如果您有两行值为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);
}