Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Implementing Cumulative total and Select All functionality with Events in ASP.NET GridView

, 17 Dec 2012
There are many scenarios in which the data can be bound in a Gridview, in which various operation other than provided by default by gridview needs to be implemented. In this article we will try to bind such operations with some more features.
EventsOfGridView.zip
EventsOfGridView
App_Data
tempdb.mdf
tempdb_log.LDF
EventsOfGridView_V2.zip
EventsOfGridView_V2
App_Data
tempdb.mdf
tempdb_log.LDF
Bin
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Default3 : System.Web.UI.Page
{
    SqlConnection conn = null;
    double lgTots = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGridView();
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGridView();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGridView();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = (int)GridView1.DataKeys[e.RowIndex].Value;
        try
        {
            using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["tempdbConn"].ConnectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Delete from tmp_table where id=@id";
                    cmd.Parameters.AddWithValue("@id", id);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            conn.Close();
        }
        BindGridView();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            lgTots += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "totalMarks"));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lgTotal = (Label)e.Row.FindControl("lblGrandTotal");
            lgTotal.Text = lgTots.ToString();
        }
    }
    protected void BindGridView()
    {
        DataTable dt = null;
        using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["tempdbConn"].ConnectionString))
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select row_number() OVER (ORDER BY id) AS sno,id,uname,totalMarks,selectedItem from tmp_table";
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    dt = new DataTable();
                    da.Fill(dt);
                }
            }
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int sid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
        string nme = string.Empty;
        TextBox tb = GridView1.Rows[e.RowIndex].Cells[3].FindControl("txtName") as TextBox;

        if (tb != null)
        {
            nme = tb.Text.Trim();
        }

        string mrks = string.Empty;
        tb = null;
        tb = GridView1.Rows[e.RowIndex].Cells[4].FindControl("txtTotalMarks") as TextBox;
        if (tb != null)
        {
            mrks = tb.Text.Trim();
        }

        CheckBox chk = GridView1.Rows[e.RowIndex].Cells[0].FindControl("chekSelect") as CheckBox;

        using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["tempdbConn"].ConnectionString))
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "UPDATE tmp_table SET uname = @nme, totalMarks = @mrks,selectedItem=@selectItem WHERE id = @sid";
                cmd.Parameters.AddWithValue("@nme", nme);
                cmd.Parameters.AddWithValue("@mrks", mrks);
                cmd.Parameters.AddWithValue("@selectItem", (chk != null) ? chk.Checked : false);
                cmd.Parameters.AddWithValue("@sid", sid);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
        GridView1.EditIndex = -1;
        BindGridView();
    }

    protected void chekSelectALL_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkA = GridView1.HeaderRow.FindControl("chekSelectALL") as CheckBox;
        foreach (GridViewRow gv in GridView1.Rows)
        {
            CheckBox chkS = gv.FindControl("chekSelect") as CheckBox;
            if (chkA.Checked)
            {
                chkS.Checked = true;
            }
            else
            {
                chkS.Checked = false;
            }
        }
    }
    protected void lnkAddNewRow_Click(object sender, EventArgs e)
    {

    }
    protected void lnkInsert_Click(object sender, EventArgs e)
    {
        string nme = string.Empty;
        TextBox tb = GridView1.FooterRow.FindControl("txtName") as TextBox;

        if (tb != null)
        {
            nme = tb.Text.Trim();
        }

        string mrks = string.Empty;
        tb = null;
        tb = GridView1.FooterRow.FindControl("txtTotalMarks") as TextBox;
        if (tb != null)
        {
            mrks = tb.Text.Trim();
        }

        bool chkSele = false;
        CheckBox chk = GridView1.FooterRow.FindControl("chekSelect") as CheckBox;

        if (chk != null)
        {
            if (chk.Checked == true)
            {
                chkSele = true;
            }
            else
            {
                chkSele = false;
            }
        }

        using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["tempdbConn"].ConnectionString))
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "Insert into tmp_table(uname,totalMarks,selectedItem) values(@nme,@mrks,@selectItem)";
                cmd.Parameters.AddWithValue("@nme", nme);
                cmd.Parameters.AddWithValue("@mrks", mrks);
                cmd.Parameters.AddWithValue("@selectItem", chkSele);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
        //  GridView1.EditIndex = -1;
        BindGridView();
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

AshishChaudha
Software Developer
India India
I am a Software Engineer from Bhopal. I started my Career from Programming in ASP and now working as a Web Developer in ASP.Net (C#). I Love coding and always ready to gain new thing and always been towards Microsoft Technologies. Apart from coding my other hobbies are traveling, Internet Surfing, spending time with family and hang out with friends.
 
http://www.webtekspace.blogspot.in/
Follow on   Twitter   Google+

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 17 Dec 2012
Article Copyright 2012 by AshishChaudha
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid