I was working on an asp.net grid and required to show the total of a column in footer row,while considering tradaitional options of using RowDataBound event and then looping through all the rows of attached datasource and then adding them to any variable and then displaying it in footer row . i just wanted to avoid those extra loops cause i wanted to show total of each column in my grid and .
so i thought of Linq to datasets options and to use sum function like
here
I used <FooterTemplate> inside <Template Field> for that specific column
my column name is WO
and code look likes here
<asp:TemplateField HeaderText="WO">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("WO") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("WO") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblFooterWO" runat="server" Text=""></asp:Label>
</FooterTemplate>
</asp:TemplateField>
Do not forget to set ShowFooter property of Grid View to True like
ShowFooter="true"
Finally in the RowDataBound event of the grid calculate the sum and bind it like
protected void grdBilling_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
//DataTable dt = ((System.Data.DataRowView)(e.Row.DataItem)).Row.Table;//.AsEnumerable();
var billing = ((DataTable)((System.Web.UI.WebControls.GridView)(sender)).DataSource).AsEnumerable();
var t = (from p in billing select p.Field<Double>("WO")).Sum();
Label lblTotal = e.Row.FindControl("lblFooterWO") as Label;
lblTotal.Text = t.ToString();
}
}
No comments:
Post a Comment