Page

Display sum of columns total in gridview footer in asp.net

// Default.aspx //


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>Show gridview Rows Total in </title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" 
        HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold ="true" 
        DataKeyNames="EmpID" runat="server" ShowFooter="True" AllowPaging="True" 
        PageSize="5" AutoGenerateColumns="False"  
        onrowdatabound="gvEmp_RowDataBound">
<FooterStyle Font-Bold="true" BackColor="#61A6F8" ForeColor="black" />
<Columns>
<asp:BoundField DataField="EmpID" HeaderText="EmpID" InsertVisible="False" 
        ReadOnly="True" SortExpression="EmpID" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
    <asp:BoundField DataField="Location" HeaderText="Location" 
        SortExpression="Location" />
    <asp:BoundField DataField="Amount" HeaderText="Amount" 
        SortExpression="Amount" />
</Columns>

<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
</form>
</body>
</html>

// Default.aspx.cs //

using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindData();
        } 
    }

    private void BindData()
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=rnp;Integrated Security=True");
        SqlDataAdapter da = new SqlDataAdapter("select * from EmployeeSalary ", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
   public int total = 0;
    protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblamount = (Label)e.Row.FindControl("lblTotal");
            lblamount.Text = total.ToString();
        }
    }
}


SQL TABLE


No comments:

Post a Comment