0

我正在使用RowDataBoundEvent 来计算列数据的总和。我得到列值总和的变量在rowdatabound事件结束时变为零,因为它的初始值为零。如何将值的总和存储在变量中以在事件之外使用其值。谢谢

int totSubTot = 0;
public double TotalAmount;
protected void gvShowOrder_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));        
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[2].Text = "Grand Total";
        e.Row.Cells[2].Font.Bold = true;

        e.Row.Cells[3].Text = totSubTot.ToString();
        e.Row.Cells[3].Font.Bold = true;
        TotalAmount = Convert.ToDouble(e.Row.Cells[3].Text);
    }
}
4

3 回答 3

3

为什么不从数据源获取总和?

var gridView = sender as GridView;
var dataSource = gridView.DataSource as IEnumerable<YourDataObject>;
e.Row.Cells[3].Text = dataSource.Sum(item => item.YourProperty).ToString();
于 2013-11-06T10:00:44.610 回答
0

你的逻辑似乎是错误的。

在您的第一个 if 语句中,您将 totSubTot 分配给 DataItem,但在您的 else 中,您没有为它分配任何东西。

它可能只进入你的 if/else if 和这就是为什么。尝试这个

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));
            TotalAmount =Convert.ToDouble(totSubTot);
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));
            TotalAmount =Convert.ToDouble(totSubTot);

            e.Row.Cells[2].Text = "Grand Total";
            e.Row.Cells[2].Font.Bold = true;

            e.Row.Cells[3].Text = totSubTot.ToString();
            e.Row.Cells[3].Font.Bold = true;
        }
于 2013-11-06T10:00:44.590 回答
0

请试试这个

static int totSubTot = 0; 
static double TotalAmount; 
protected void gvShowOrder_RowDataBound(object sender, GridViewRowEventArgs e) {
    if (e.Row.RowType == DataControlRowType.DataRow) {
        totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));        
    } else if (e.Row.RowType == DataControlRowType.Footer) {
        e.Row.Cells[2].Text = "Grand Total";
        e.Row.Cells[2].Font.Bold = true;

        e.Row.Cells[3].Text = totSubTot.ToString();
        e.Row.Cells[3].Font.Bold = true;
        TotalAmount = Convert.ToDouble(e.Row.Cells[3].Text);
    }
}
于 2015-01-01T15:13:56.067 回答