如何在gridview中为动态列添加子总计

时间:2012-05-28 13:12:48

标签: asp.net gridview

如何在gridview

中添加动态列的子总计
region  customer 01-feb-2012 02-feb-2012 ...... 29-feb-2012 Total
chennai xxx               10          20                       30
        yyy               10                                   10
        Total             20          20                       40
mumbai  aaa               20                                   20
        bbb                           10                       10
        Total             20          10                       30

没有。列的数量取决于所选月份的天数。

2 个答案:

答案 0 :(得分:0)

我建议你不要在网格视图中计算它,而是建议你在数据表级别进行,而不是将数据表与网格视图绑定,因为在网格视图中进行操作会使其变得复杂。

答案 1 :(得分:0)

我已经为你提供了示例代码......

在您的代码中引用此代码,它将动态计算总值。使用DataRowBound属性,其工作...

Aspx代码:

<asp:GridView ID="grdBoardingListReport" runat="server" CellPadding="2" ForeColor="#333333" GridLines="Both" AutoGenerateColumns="false" ShowFooter="false">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#c5c5c5" Font-Bold="True" HorizontalAlign="Right" />
<HeaderStyle CssClass="clsReportGridHeader" BackColor="#c5c5c5" Font-Size="10"/>
<PagerStyle BackColor="#39afd9" ForeColor="White" HorizontalAlign="Center"/>
<Columns>
<asp:BoundField DataField="Sl.No" HeaderText="slno" />
<asp:BoundField DataField="fd_name" HeaderText="Name" />
<asp:BoundField DataField="fd_total" HeaderText="Total"/>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>

代码绑定:

private void bindFreePassReport()
{
if (!(Session["FreePassReceive"] == null))
{
DataTable freePassReceive = (DataTable)Session["FreePassReceive"];

if (freePassReceive.Rows.Count > 1)
{
grdFreePassReport.DataSource = freePassReceive;
grdFreePassReport.DataBind();
lblTitle.Text = Session["FreePassReportTitle"].ToString();
}
else
{
grdFreePassReport.DataSource = null;
grdFreePassReport.DataBind();
}
}
}

Datarow Bound:

int Total;
protected void grdBordingPlace_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
total += Convert.ToInt32(e.Row.Cells[2].Text);
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Text = "Total" + " : ";
e.Row.Cells[2].Text = total.ToString();
}
}