简体   繁体   English

使用for循环获取GridView Cloumn的总和

[英]Getting sum of gridview cloumn using for loop

I am trying to get sum of grid-view column using for loop and put it in label 我正在尝试使用for循环获取网格视图列的总和并将其放在标签中

i have tried below code but it give me incorrect result 我试过下面的代码,但它给我错误的结果

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);

    }
}

The RowDataBound event is called foreach row. RowDataBound事件称为foreach行。 So, if you have two rows with a value of 10 you will be called two times. 因此,如果您有两行,其值为10,则将被两次调用。 The first time the total is correct, but the second time it keeps incrementing the total and you end up with a total of 40. 第一次总计是正确的,但是第二次它一直在增加总计,您最终得到40。

You should move your loop after the DataBind(), something like this.... 您应该将循环移动到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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM