以下是我的gridview:
<asp:GridView ID="gv_TotalAllReg" runat="server" AutoGenerateColumns="false" OnRowDataBound="gv_TotalAllReg_RowDataBound" DataKeyNames="dt" CssClass="table table-bordered table-striped">
<Columns>
<asp:TemplateField HeaderText="Sno" HeaderStyle-BackColor="#f1f1f1">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="dt" DataFormatString="{0:MM-dd-yyyy}" HeaderText="Date" />
<asp:TemplateField HeaderText="New Registrations">
<ItemTemplate>
<asp:Label ID="lbl_Registrations" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cumulative Registrations">
<ItemTemplate>
<asp:Label ID="lbl_CumulativeRegistrations" runat="server"></asp:Label>
</ItemTemplate>
</Columns>
</asp:GridView>
下面我试图实现计数。
我正在显示日期明智的新注册,但我需要基于新注册的累积注册:
Sno Date New Registrations Cumulative Registrations
1 12-23-2016 2
2 12-24-2016 6
3 12-25-2016 1
我需要输出如下,累积注册意味着我已经为2016年12月23日至25日的显示日期创建了一个功能。所以根据日期获得新的注册,我也希望显示基于新注册的累积注册,基于新的注册添加暨注册以及如何实现暨注册在RowDataBound中添加相反的顺序。
Sno Date New Registrations Cumulative Registrations
1 12-25-2016 2 9
2 12-24-2016 6 7
3 12-23-2016 1 1
下面我有代码并计算升序添加,但我需要添加逆序
int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the current row to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//add the registrations to the total
total += Convert.ToInt32(row["Registrations"]);
//find the label in the row with findcontrol and cast it back to one
Label label = e.Row.FindControl("lbl_CumulativeRegistrations") as Label;
//fill the label with the current total
label.Text = string.Format("{0:N0}", total);
}
}
我正在按照升序格式输出输出
Cumulative Registrations
2
8
9
答案 0 :(得分:1)
此代码向数据源(数据表)添加一个新列并汇总所有注册。
你可以在gridview数据绑定之前放置并删除ItemDatabound方法。
//tbl is your datasoure (DataTable)
tbl.Columns.Add("TotalRegistration", typeof(long));
long total = 0;
for (int i = tbl.Rows.Count -1; i >= 0; i--)
{
total += (int)tbl.Rows[i]["Registrations"]; // if columnd type is not int, use Convert.ToInt32
tbl.Rows[i]["TotalRegistration"] = total;
}