Dec 24, 2011

Displaying Total in ASP.NET Gridview Footer Row Without using Template Field

There are tons of articles to display total in asp.net gridview footer row. The common approach to implement this is:

1. Create template field of the column which is to be totalled.

2. Define FooterTemplate and add Label control.

3. Take a variable and add value of each row in GridView1_RowDataBound event.

4. Find label control in footer and assign the variable.

It's too complex. Let's see how to take advantage of LINQ or Lambda expression and skip these steps.

gridview footer asp.net row total

See following code

 
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="true">
        <Columns>
            <asp:BoundField DataField="Class" HeaderText="Class" FooterText="Total" />
            <asp:BoundField DataField="Students" HeaderText="Students" />
        </Columns>
    </asp:GridView>

The above grid displays total number of students of the class. Now, we have to show total number of students of all classes in footer row.


	protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }

    void BindGrid(){
        DataTable dt = GetTotalStudents();
        GridView1.Columns[1].FooterText =  dt.AsEnumerable().Select(x => x.Field<int>("Students")).Sum().ToString();   
        GridView1.DataSource = dt;
        GridView1.DataBind(); 
    }

It's so simple !!! One line of code has done the task. No need to take template field and add row value in RowDataBound event.

In other way(using LINQ):


 GridView1.Columns[1].FooterText = (from row in dt.AsEnumerable()
                                    select row.Field<int>("Students")).Sum().ToString();   

Hope, It helps.