Quantcast
Channel: TechBrij
Viewing all articles
Browse latest Browse all 116

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

$
0
0


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%20footer%20row%20total Displaying Total in ASP.NET Gridview Footer Row Without using Template Field
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.

Related posts:

  1. Bind array to specific column of asp.net gridview
  2. Show ModalPopUp to Edit Asp.net Gridview Row Values Without using AjaxControlToolkit
  3. Adding Gridview nested in Repeater in ASP.NET 2.0
  4. Retrieve value of Dynamic controls in asp.net
  5. Create Dynamic DropDownLists in asp.net

Viewing all articles
Browse latest Browse all 116

Trending Articles