47
GridView CRUD: Select Insert Edit Update Delete using Single Stored Procedure in ASP.Net http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit- Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx Database I have made use of the following table Customers with the schema as follows. I have already inserted few records in the table. HTML Markup The HTML Markup consists of an ASP.Net GridView with multiple event handlers assigned which will be discussed later. The GridView has a CommandField column which will display the command buttons i.e. Edit, Update, Cancel and Delete. Below the GridView there’s a Form which will allow us to insert data to the SQL Server database table. .aspx page(html section)

ASP GridView Practicals

  • Upload
    vip

  • View
    50

  • Download
    3

Embed Size (px)

DESCRIPTION

Gives step by step

Citation preview

Page 1: ASP GridView Practicals

GridView CRUD: Select Insert Edit Update Delete using Single Stored Procedure in ASP.Net

http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-Update-Delete-using-Single-Stored-Procedure-in-ASPNet.aspx

Database

I have made use of the following table Customers with the schema as follows.

I have already inserted few records in the table.

HTML Markup

The HTML Markup consists of an ASP.Net GridView with multiple event handlers assigned which will be discussed later.

The GridView has a CommandField column which will display the command buttons i.e. Edit, Update, Cancel and Delete.

Below the GridView there’s a Form which will allow us to insert data to the SQL Server database table.

.aspx page(html section)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="CustomerId"

Page 2: ASP GridView Practicals

OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added."><Columns>    <asp:TemplateField HeaderText="Name" ItemStyle-Width="150">        <ItemTemplate>            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>        </ItemTemplate>        <EditItemTemplate>            <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>        </EditItemTemplate>    </asp:TemplateField>    <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">        <ItemTemplate>            <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>        </ItemTemplate>        <EditItemTemplate>            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>        </EditItemTemplate>    </asp:TemplateField>    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/></Columns></asp:GridView><table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse"><tr>    <td style="width: 150px">        Name:<br />        <asp:TextBox ID="txtName" runat="server" Width="140" />    </td>    <td style="width: 150px">        Country:<br />        <asp:TextBox ID="txtCountry" runat="server" Width="140" />    </td>    <td style="width: 100px">        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />    </td></tr></table>

 

Stored Procedure for Select, Insert, Update and Delete

Page 3: ASP GridView Practicals

The following stored procedure will be used to perform Select, Insert, Update and Delete operations on the SQL Server database table.

CREATE PROCEDURE [dbo].[Customers_CRUD]

      @Action VARCHAR(10)

      ,@CustomerId INT = NULL

      ,@Name VARCHAR(100) = NULL

      ,@Country VARCHAR(100) = NULL

AS

BEGIN

      SET NOCOUNT ON;

 

      --SELECT

    IF @Action = 'SELECT'

      BEGIN

            SELECT CustomerId, Name, Country

            FROM Customers

      END

 

      --INSERT

    IF @Action = 'INSERT'

      BEGIN

            INSERT INTO Customers(Name, Country)

            VALUES (@Name, @Country)

      END

 

      --UPDATE

    IF @Action = 'UPDATE'

      BEGIN

            UPDATE Customers

            SET Name = @Name, Country = @Country

            WHERE CustomerId = @CustomerId

      END

 

      --DELETE

    IF @Action = 'DELETE'

      BEGIN

            DELETE FROM Customers

            WHERE CustomerId = @CustomerId

      END

END

 

.aspx.cs page

Namespaces

You will need to import the following namespaces.

C#

Page 4: ASP GridView Practicals

using System.Data;using System.Configuration;using System.Data.SqlClient;

Binding the GridView with records from SQL Database Table

The GridView is populated from the database inside the Page Load event of the page. Here the stored procedure is being called with the Action parameter value as “SELECT”.

protected void Page_Load(object sender, EventArgs e){    if (!this.IsPostBack)    {        this.BindGrid();    }}

 private void BindGrid(){    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;    using (SqlConnection con = new SqlConnection(constr))    {        using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))        {            cmd.Parameters.AddWithValue("@Action", "SELECT");            using (SqlDataAdapter sda = new SqlDataAdapter())            {                cmd.CommandType = CommandType.StoredProcedure;                cmd.Connection = con;                sda.SelectCommand = cmd;                using (DataTable dt = new DataTable())                {                    sda.Fill(dt);                    GridView1.DataSource = dt;                    GridView1.DataBind();                }            }        }    }} OUTPUT

Page 5: ASP GridView Practicals

 For the GridView I have set EmptyDataText to display message when no records are present.

Inserting records to GridView

The following event handler is executed when the Add Button is clicked. The name and the country values are fetched from their respective TextBoxes and then passed to the Stored Procedure with Action parameter value as “INSERT”.

Finally the GridView is again populated with data by making call to the BindGrid method.

protected void Insert(object sender, EventArgs e){    string name = txtName.Text;    string country = txtCountry.Text;    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;    using (SqlConnection con = new SqlConnection(constr))    {        using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))        {            cmd.CommandType = CommandType.StoredProcedure;            cmd.Parameters.AddWithValue("@Action", "INSERT");            cmd.Parameters.AddWithValue("@Name", name);            cmd.Parameters.AddWithValue("@Country", country);            cmd.Connection = con;            con.Open();            cmd.ExecuteNonQuery();            con.Close();        }    }    this.BindGrid();}

Editing and Updating GridView records

Edit

Page 6: ASP GridView Practicals

When the Edit Button is clicked, the GridView’s OnRowEditing event handler is triggered. Here simply the EditIndex of the GridView is updated with the Row Index of the GridView Row to be edited.

protected void OnRowEditing(object sender, GridViewEditEventArgs e){    GridView1.EditIndex = e.NewEditIndex;    this.BindGrid();}

Update

When the Update Button is clicked, the GridView’s OnRowUpdating event handler is triggered.

CustomerId which is the primary key is fetched from the DataKey property of GridView while the Name and Country fields are fetched from their respective TextBoxes and are passed to the Stored Procedure with Action parameter value as “UPDATE”.

protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e){    GridViewRow row = GridView1.Rows[e.RowIndex];    int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);    string name = (row.FindControl("txtName") as TextBox).Text;    string country = (row.FindControl("txtCountry") as TextBox).Text;    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;    using (SqlConnection con = new SqlConnection(constr))    {        using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))        {            cmd.CommandType = CommandType.StoredProcedure;            cmd.Parameters.AddWithValue("@Action", "UPDATE");            cmd.Parameters.AddWithValue("@CustomerId", customerId);            cmd.Parameters.AddWithValue("@Name", name);            cmd.Parameters.AddWithValue("@Country", country);            cmd.Connection = con;            con.Open();            cmd.ExecuteNonQuery();            con.Close();        }    }    GridView1.EditIndex = -1; // //GridView has Indexes, 0 means edit mode, -1 means readonly mode

    this.BindGrid(); // Once the gridview mode is changed to 0, we have to pull the data

}

Cancel Edit

Page 7: ASP GridView Practicals

When the Cancel Button is clicked, the GridView’s OnRowCancelingEdit event handler is triggered. Here the EditIndex is set to -1 and the GridView is populated with data.

protected void OnRowCancelingEdit(object sender, EventArgs e){    GridView1.EditIndex = -1;// Once Gridview Update is cancelled, then we have to set the index of GridView to

readonly mode.

    this.BindGrid(); //reload}

o/p

Deleting GridView records

When the Delete Button is clicked, the GridView’s OnRowDeleting event handler is triggered.

CustomerId which is the primary key is fetched from the DataKey property of GridView and is passed to the Stored Procedure along with the Action parameter value as “DELETE”.

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e){    int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;    using (SqlConnection con = new SqlConnection(constr))    {        using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))        {            cmd.CommandType = CommandType.StoredProcedure;            cmd.Parameters.AddWithValue("@Action", "DELETE");            cmd.Parameters.AddWithValue("@CustomerId", customerId);            cmd.Connection = con;            con.Open();            cmd.ExecuteNonQuery();            con.Close();        }    }    this.BindGrid();}

Page 8: ASP GridView Practicals

 CONFIRM MESSAGE BOX :- when deleting row, I have made use of OnRowDataBound event handler where I have first determined the Delete Button and then I have attach the JavaScript Confirm to its client side Click event handler.

protected void OnRowDataBound(object sender, GridViewRowEventArgs e){    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)    {        (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";N.B :- ((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text {complete with sini)

    }}

o/p

3 Ways to implement CRUD (Select, Insert, Update, Delete) Operations

1. Separate Pages:

In this approach, Data is displayed in Grid with Edit and Delete options. There is also link to add New

record. When user clicks to add new item, the page is redirected to another page having different

controls with default values, instructions and validators. After entering data, when user submits form,

It is redirected to back on Grid page with new entry.

Page 9: ASP GridView Practicals

When user clicks on edit option of any record, It is redirected to page with filled form. Generally same

form is used with query-string parameter to retrieve data from database, fill form and to differentiate

add /edit operations.

This approach is useful when form has many fields and structure is complex.

2. Pop-Up Form:

In this approach, Pop-up dialog instead of separate page

is used to Add/Edit data. When user clicks on New option, blank modal pop-up form is displayed and

On submission, It’s closed automatically. On editing, filled pop-up form is displayed, user modifies

values and save it.

This approach is useful when form has limited fields and Ajax based page(like dashboard) is used. See

following post to implement this approach in ASP.NET:

3. Inline Editing:

In this approach, all operations are done in Grid. When user clicks on edit option, all items become

editable and on saving, again become read only.

Show ModalPopUp to Edit Asp.net Gridview Row Values Without using

AjaxControlToolkit (using Jquery) http://techbrij.com/show-modal-popup-edit-aspdotnet-gridview

Page 10: ASP GridView Practicals

This article explains how to add a pop-up control to a gridview in order to display drill-down (Master

detail) information without using ajaxcontroltoolkit ModalPopup extender. let us take an example to

display Northwind database’s customer table.

GridView Structure:

<asp:GridView ID="GridViewData" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"

            OnRowCommand="GridViewData_RowCommand">

            <Columns>

                <asp:BoundField DataField="CustomerID" HeaderText="Customer ID" />

                <asp:BoundField DataField="CompanyName" HeaderText="Company Name" />

                <asp:BoundField DataField="ContactName" HeaderText="Contact Name" />

                <asp:BoundField DataField="Address" HeaderText="Address" />

                <asp:BoundField DataField="City" HeaderText="City" />

                <asp:TemplateField HeaderText="" SortExpression="">

                    <ItemTemplate>

                        <asp:LinkButton ID="LinkButtonEdit" runat="server" CommandName="ShowPopup"

CommandArgument='<%#Eval("CustomerID") %>'>Edit</asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

Page 11: ASP GridView Practicals

        </asp:GridView>

Bind Data to GridView:

?

DataTable dt = new DataTable();

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings

["NorthwindConnectionString"].ToString());

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                Bind();

            }

        }

        protected void Bind()

        {

            con.Open();

            SqlCommand cmd = new SqlCommand("SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers] ", con);

            cmd.CommandType = CommandType.Text;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(dt);

            GridViewData.DataSource = dt;

            GridViewData.DataBind();

        }

Popup Structure:

?

<style type="text/css">

       

Page 12: ASP GridView Practicals

        #mask

        {

            position: fixed;

            left: 0px;

            top: 0px;

            z-index: 4;

            opacity: 0.4;

            -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=40)"; /* first!*/

            filter: alpha(opacity=40); /* second!*/

            background-color: gray;

            display: none;

            width: 100%;

            height: 100%;

        }

    </style>

    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript">

        function ShowPopup() {

            $('#mask').show();

            $('#<%=pnlpopup.ClientID %>').show();

        }

        function HidePopup() {

            $('#mask').hide();

            $('#<%=pnlpopup.ClientID %>').hide();

        }

        $(".btnClose").live('click',function () {

            HidePopup();

Page 13: ASP GridView Practicals

        });

    </script>

    <div id="mask">

    </div>

      <asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="175px"

            Width="300px" Style="z-index:111;background-color: White; position: absolute; left: 35%; top: 12%;

border: outset 2px gray;padding:5px;display:none">

            <table width="100%" style="width: 100%; height: 100%;" cellpadding="0" cellspacing="5">

                <tr style="background-color: #0924BC">

                    <td colspan="2" style="color:White; font-weight: bold; font-size: 1.2em; padding:3px"

                        align="center">

                        Customer Details <a id="closebtn" style="color: white; float: right;text-decoration:none" class="btnClose" href="#">X</a>

                    </td>

                </tr>

                <tr>

                    <td colspan="2" style="width: 45%; text-align: center;">

                        <asp:Label ID="LabelValidate" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td align="right" style="width: 45%">

                        CustomerID:

                    </td>

                    <td>

Page 14: ASP GridView Practicals

                        <asp:Label ID="lblID" runat="server"></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td align="right">

                        Contact Name:

                    </td>

                    <td>

                        <asp:Label ID="lblContactName" runat="server"></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td align="right">

                        Address:

                    </td>

                    <td>

                        <asp:TextBox ID="txtAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td align="right">

                        City:

                    </td>

                    <td>

                        <asp:TextBox ID="txtCity" runat="server" />

                    </td>

                </tr>

Page 15: ASP GridView Practicals

                <tr>

                    <td>

                    </td>

                    <td>

                        <asp:Button ID="btnUpdate" CommandName="Update" runat="server" Text="Update" OnClick="btnUpdate_Click" />

                        <input type="button" class="btnClose" value="Cancel" />

                    </td>

                </tr>

            </table>

        </asp:Panel>

Here mask div is used as a layer to block page elements and pnlpopup will be displayed as

popup.

Show & Edit data:

?

protected void GridViewData_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            if (e.CommandName == "ShowPopup")

            {

                LinkButton btndetails = (LinkButton)e.CommandSource;

                GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;

                lblID.Text = GridViewData.DataKeys[gvrow.RowIndex].Value.ToString();

                // DataRow dr = dt.Select("CustomerID=" + GridViewData.DataKeys[gvrow.RowIndex].Value.ToString())[0];

                lblContactName.Text = HttpUtility.HtmlDecode(gvrow.Cells[2].Text);

                txtAddress.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text);

Page 16: ASP GridView Practicals

                txtCity.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);

                Popup(true);

            }

        }

        protected void btnUpdate_Click(object sender, EventArgs e)

        {

            if (txtAddress.Text == "")

            {

                LabelValidate.Text = "Please enter the address.";

                LabelValidate.ForeColor = Color.Red;

            }

            else

            {

                con.Open();

                SqlCommand cmd = new SqlCommand("update Customers set Address=@Address,City=@City where CustomerID=@CustomerID", con);

                cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

                cmd.Parameters.AddWithValue("@City", txtCity.Text);

                cmd.Parameters.AddWithValue("@CustomerID", lblID.Text);

                cmd.ExecuteNonQuery();

                con.Close();

                lblresult.Text = lblContactName.Text + " Details Updated Successfully";

                lblresult.ForeColor = Color.Green;

                Bind();

                Popup(false);

            }

Page 17: ASP GridView Practicals

        }

        //To show message after performing operations

        void Popup(bool isDisplay)

        {

            StringBuilder builder = new StringBuilder();

            if (isDisplay)

            {

                builder.Append("<script language=JavaScript> ShowPopup(); </script>\n");

                Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowPopup", builder.ToString());

            }

            else

            {

                builder.Append("<script language=JavaScript> HidePopup(); </script>\n");

                Page.ClientScript.RegisterStartupScript(this.GetType(), "HidePopup", builder.ToString());

            }

        }

Convert TimeSpan to year, month, date (Age Calculation) in .NETGenerally, it is required to express Datetime difference in terms of year, month or day

format. Basic example of this is the Age calculation. In .NET Date difference is expressed in

timespan. If you require age only in Year then

?

//txt1 = TextBox for Birthdate Input.        DateTime dt1 = Convert.ToDateTime(txt1.Text);        DateTime dt2 = DateTime.Now;         if (dt1.DayOfYear <= dt2.DayOfYear)        {            lbl.Text = (dt2.Year-dt1.Year).ToString();          }        else        {

Page 18: ASP GridView Practicals

            lbl.Text = (dt2.Year-dt1.Year - 1).ToString();          }

But if you require month and date as well

?

protected void btn_Click(object sender, EventArgs e)    {        int years=-1,months=-1,days=-1;        DateTime birthDate = Convert.ToDateTime(txt1.Text);        TimeSpanToDate (DateTime.Now, birthDate,out years,out months,out days);        Response.Write("Years: "+ years.ToString()+ " Months: "+ months.ToString()+" Days: "+ days.ToString());      }public void TimeSpanToDate(DateTime d1, DateTime d2,out int years, out int months, out int days){// compute & return the difference of two dates,// returning years, months & days// d1 should be the larger (newest) of the two dates// we want d1 to be the larger (newest) date// flip if we need toif (d1 < d2){DateTime d3= d2;d2= d1;d1= d3;}

 // compute difference in total monthsmonths= 12 * (d1.Year - d2.Year) + (d1.Month - d2.Month);

 // based upon the 'days',// adjust months & compute actual days differenceif (d1.Day < d2.Day){months--;days = DateTime.DaysInMonth(d2.Year, d2.Month) - d2.Day + d1.Day;}else{days= d1.Day - d2.Day;}// compute years & actual monthsyears= months / 12;months-= years * 12;}   

Page 19: ASP GridView Practicals

Displaying Total in ASP.NET Gridview Footer Row Without using Template Field(using Enum)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.

<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(); }

Page 20: ASP GridView Practicals

N.B: In other way(using LINQ):

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

Dynamically change GridView Row Background Color based on condition in ASP.Net

http://www.aspsnippets.com/Articles/Dynamically-change-GridView-Row-Background-Color-based-on-condition-in-ASPNet-using-C-and-VBNet.aspx

GridView HTML Markup

<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound">    <Columns>        <asp:BoundField DataField="Item" HeaderText="Item"/>        <asp:BoundField DataField="Quantity" HeaderText="Quantity"/>    </Columns></asp:GridView>

 

Namespaces

You will need to import the following namespaces

using System.Data;using System.Drawing;

Binding the ASP.Net GridView control

I have used a DataTable to bind the GridView with data in the following way

protected void Page_Load(object sender, EventArgs e){    if (!IsPostBack)    {        DataTable dt = new DataTable();        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Quantity") });        dt.Rows.Add("Shirt", 145);        dt.Rows.Add("Jeans", 0);        dt.Rows.Add("Trousers", 190);        dt.Rows.Add("Tie", 30);        dt.Rows.Add("Cap", 0);

Page 21: ASP GridView Practicals

        dt.Rows.Add("Hat", 90);        dt.Rows.Add("Scarf", 290);        dt.Rows.Add("Belt", 150);        GridView1.DataSource = dt;        GridView1.DataBind();    }}

N.B:- Intrvw Questn :-

Bind gridview with value that doesn’t saved in the database. (ans above)

Changing the Background color of GridView Row as per condition dynamically

Using the GridView OnRowDataBound event I am checking the different quantity ranges and based on the quantity values I am setting the background color of the GridView Row as per the following conditions

 

Quantity Range Background Color0 RED1 - 50 YELLOW51 - 100 ORANGE

 

protected void OnRowDataBound(object sender, GridViewRowEventArgs e){    if (e.Row.RowType == DataControlRowType.DataRow)    {        int quantity = int.Parse(e.Row.Cells[1].Text);

         foreach (TableCell cell in e.Row.Cells)        {            if (quantity == 0)            {                cell.BackColor = Color.Red;            }            if (quantity > 0 && quantity <= 50)            {                cell.BackColor = Color.Yellow;            }            if (quantity > 50 && quantity <= 100)            {                cell.BackColor = Color.Orange;            }        }    }} 

 

Page 22: ASP GridView Practicals

Bind Dropdownlist in Gridview in Asp.net using Datasethttp://www.aspdotnet-suresh.com/2015/02/bind-dropdownlist-in-gridview-in-aspnet-using-dataset-

csharp-vbnet.html

Here I will explain how to bind data to dropdownlist in gridview in asp.net using dataset

or populatedropdownlist in gridview in asp.net using dataset. we can bind dropdownlist in gridview

using ItemTemplate field.

To implement this concept first design tables in your database as explained in this post populate dropdown based on another dropdown in asp.net . After that design your aspx page like this 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Asp.net Bind Data to Dropdownlist in inside of gridview</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="gvUserInfo" runat="server" AutoGenerateColumns="false"OnRowDataBound="gvUserInfo_RowDataBound" >

<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />

<Columns>

<asp:BoundField DataField="CountryId" HeaderText="CountryId" />

<asp:BoundField DataField="CountryName" HeaderText="CountryName" />

<asp:TemplateField HeaderText="Location">

<ItemTemplate>

<asp:DropDownList ID="ddlCity" runat="server" Width="100px"/>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</div>

</form>

</body>

</html>

Now add following namespaces in codebehind

C# Code

using System;

using System.Data;

using System.Data.SqlClient;

Page 23: ASP GridView Practicals

using System.Web.UI;

using System.Web.UI.WebControls;

After that add following code in code behind

SqlConnection con =new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindGridview();

}

}

// This method is used to bind gridview from database

protected void BindGridview()

{

con.Open();

SqlCommand cmd = new SqlCommand("select TOP 4 CountryId,CountryName from Country", con);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

con.Close();

gvUserInfo.DataSource = ds;

gvUserInfo.DataBind();

}

protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

con.Open();

var ddl = (DropDownList)e.Row.FindControl("ddlCity");

int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);

SqlCommand cmd = new SqlCommand("select * from State where CountryID=" + CountryId, con);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

con.Close();

ddl.DataSource = ds;

ddl.DataTextField = "StateName";

ddl.DataValueField = "StateID";

ddl.DataBind();

ddl.Items.Insert(0, new ListItem("--Select--", "0"));

}

}

O/ p

Page 24: ASP GridView Practicals

Delete Multiple Rows in Gridview using Checkbox in Asp.nethttp://www.aspdotnet-suresh.com/2014/12/delete-multiple-rows-in-gridview-using-checkbox-in-aspnet-in-csharp-

vbnet.html

delete multiple rows in gridview using checkbox in asp.net in c# , vb.net with confirmation message or delete

multiple rows or records from gridview using checkbox selection with confirmation in asp.net using c#

first design one table UserDetails in your database as shown below

Column Name Data Type Allow Nulls

UserId Int(IDENTITY=TRUE) Yes

UserName varchar(50) Yes

FirstName varchar(50) Yes

LastName varchar(50) Yes

Once table created in database enter some dummy data to test application after that write the following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>how to delete Multiple Rows from gridview in asp.net using checkbox</title>

<script type="text/javascript">

function Confirmationbox() {

var result = confirm('Are you sure you want to delete selected User(s)?');

if (result) {

return true;

}

else {

return false;

}

}

</script>

</head>

<body>

<form id="form1" runat="server">

Page 25: ASP GridView Practicals

<div>

<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5"runat="server">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:CheckBox ID="chkSelect" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="UserId" DataField="UserId" />

<asp:BoundField HeaderText="UserName" DataField="UserName" />

<asp:BoundField HeaderText="FirstName" DataField="FirstName" />

<asp:BoundField HeaderText="LastName" DataField="LastName" />

</Columns>

<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />

</asp:GridView>

<asp:Button ID="btnDelete" Text="Delete Selected Records" runat="server" Font-Bold="true"OnClientClick="javascript:return

Confirmationbox();" onclick="btnDelete_Click" />

</div>

</form>

</body>

</html>

Now open code behind file and write the following code

C# Code

using System;

using System.Data;

using System.Data.SqlClient;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class DeleteGridviewRows : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindUserDetails();

}

}

protected void BindUserDetails()

{

DataTable dt = new DataTable();

using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))

{

con.Open();

SqlCommand cmd = new SqlCommand("Select * from UserDetails", con);

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(dt);

con.Close();

}

Page 26: ASP GridView Practicals

gvDetails.DataSource = dt;

gvDetails.DataBind();

}

protected void btnDelete_Click(object sender, EventArgs e)

{

foreach (GridViewRow gvrow in gvDetails.Rows)

{

//Finiding checkbox control in gridview for particular row

CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");

//Condition to check checkbox selected or not

if (chkdelete.Checked)

{

//Getting UserId of particular row using datakey value

int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);

using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))

{

con.Open();

SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);

cmd.ExecuteNonQuery();

con.Close();

}

}

}

BindUserDetails();

}

}

O/P

How to Export Data to Excel from Datatable or Gridview in Asp.net http://www.aspdotnet-suresh.com/2014/11/export-data-to-excel-from-datatable-gridview-aspnet-csharp.html

To export data to excel from datatable or dataset in asp.net using c# 

Page 27: ASP GridView Practicals

To export data to excel from datatable or gridview we need to write the code like as shown below in aspx page

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Export Data to Excel from datatable or gridview in Asp.net</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">

<Columns>

<asp:BoundField HeaderText="UserId" DataField="UserId" />

<asp:BoundField HeaderText="UserName" DataField="UserName" />

<asp:BoundField HeaderText="Education" DataField="Education" />

<asp:BoundField HeaderText="Location" DataField="Location" />

</Columns>

<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />

</asp:GridView>

</div>

<asp:Button ID="btnExport" runat="server" Text="Export to Excel from Gridview"

onclick="btnExport_Click" />

<asp:Button ID="btnExportTable" runat="server" Text="Export to Excel from Datatable"

onclick="btnExportTable_Click" />

</form>

</body>

</html>

Now in code behind we need to write the code as like shown below

C#.NET Code

using System;

using System.Data;

using System.IO;

using System.Web.UI;

public partial class ExportExceldatatoDatatable : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

gvDetails.DataSource = BindDatatable();

gvDetails.DataBind();

}

}

protected DataTable BindDatatable()

{

DataTable dt = new DataTable();

Page 28: ASP GridView Practicals

dt.Columns.Add("UserId", typeof(Int32));

dt.Columns.Add("UserName", typeof(string));

dt.Columns.Add("Education", typeof(string));

dt.Columns.Add("Location", typeof(string));

dt.Rows.Add(1, "SureshDasari", "B.Tech", "Chennai");

dt.Rows.Add(2, "MadhavSai", "MBA", "Nagpur");

dt.Rows.Add(3, "MaheshDasari", "B.Tech", "Nuzividu");

dt.Rows.Add(4, "Rohini", "MSC", "Chennai");

dt.Rows.Add(5, "Mahendra", "CA", "Guntur");

dt.Rows.Add(6, "Honey", "B.Tech", "Nagpur");

return dt;

}

public override void VerifyRenderingInServerForm(Control control)

{

/* Verifies that the control is rendered */

}

// Export data to Excel from Gridview

protected void btnExport_Click(object sender, EventArgs e)

{

Response.ClearContent();

Response.Buffer = true;

Response.AddHeader("content-disposition", string.Format("attachment; filename={0}","Customers.xls"));

Response.ContentType = "application/ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvDetails.AllowPaging = false;

gvDetails.DataSource = BindDatatable();

gvDetails.DataBind();

//Change the Header Row back to white color

gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");

//Applying stlye to gridview header cells

for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)

{

gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");

}

gvDetails.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

}

//Export data to excel from datatable

protected void btnExportTable_Click(object sender, EventArgs e)

{

Response.ClearContent();

Response.Buffer = true;

Response.AddHeader("content-disposition", string.Format("attachment; filename={0}","Customers.xls"));

Response.ContentType = "application/ms-excel";

DataTable dt = BindDatatable();

string str = string.Empty;

foreach (DataColumn dtcol in dt.Columns)

{

Response.Write(str + dtcol.ColumnName);

Page 29: ASP GridView Practicals

str = "\t";

}

Response.Write("\n");

foreach (DataRow dr in dt.Rows)

{

str = "";

for (int j = 0; j < dt.Columns.Count; j++)

{

Response.Write(str + Convert.ToString(dr[j]));

str = "\t";

}

Response.Write("\n");

}

Response.End();

}

}

N.B :-If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control

must be placed in inside of form tag”. If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before

exporting and our functionality will work perfectly.

O/P

GridView Sorting

http://www.dotnetinterviewquestions.in/article_aspnet-interview-questions:-can-you-explain-method-of-sorting-

gridviewcontrol-in-aspnet_4.html

Sorting: - Sorting allow you to sort the GridViewcontrol data in Ascending or Descending order.

Let's demonstrate a simple example to see how exactly we can sort the GridView Control.

In order to sort the GridView control you need to follow the following steps.

Step1: - Create a new Project > Go to file > New > Project > ASP.NET Empty Web Application.

Page 30: ASP GridView Practicals

Now, Add a Web Form in to your application.

Go to Solution explorer > Right click on the project name> Select Add > Add New Item > Select Web Form and click Add.

Step2: -Now on the WebForm1 design modes just drag and drop GridView control from the ToolBox.

In the above diagram of GridView Control you see that the circled column is inblack color, now just go to properties of GridView control

set AllowSorting to true and also set AutoGenerateColumns to false.

As soon as you set Allowsorting to true will find the GridView control like below diagram.

In the above diagram you see that now the color of the circle columns is in  blue color with underline on it this indicates that you can now sort

the GridView control.

Step3: -Go to source of the page and add the following in to it.

Page 31: ASP GridView Practicals

In the above code snippet you can see that I have called GridView1_Sorting event on OnSorting property and in the

columnBoundField just have allow SortExpression on StudentName column. 

Step4: -Now go to Webform1.aspx.cs and add the below code snippet.

Page 32: ASP GridView Practicals

Once you have done with the above steps now run your application and will see output like below diagram.

The result above is displayed according to the data in theSQLServer table, now just click on StudentName and will find result like below

diagram.

Now, you can see that GridViewdata has been sorted in Descending order and if you again click on StudentName now the data will be sorted

in Ascending order.

Using JavaScript with ASP.Net GridView Control

http://www.aspsnippets.com/Articles/Using-JavaScript-with-ASPNet-GridView-Control.aspx

In this Article, I am explaining how to make use JavaScript in the ASP.Net GridView control and make it more elegant by reducing postbacks.

Functions such as

1.     Highlighting selected row2.     Check/Uncheck all records using single checkbox.

Page 33: ASP GridView Practicals

3.     Highlight row on mouseover event.

The above three functions can be easily achieved using JavaScript thus avoiding postbacks.

 Basic Concept

 The basic concept behind this is when the GridView is rendered on the client machine it is rendered as a simple HTML table. Hence what the JavaScript will see a HTML table and not the ASP.Net GridView control.

Hence once can easily write scripts for GridView, DataGrid and other controls once you know how they are rendered.

 To start with I have a GridView control with a header checkbox and checkbox for each individual record

<asp:GridView ID="GridView1" runat="server"  HeaderStyle-CssClass = "header"

AutoGenerateColumns = "false" Font-Names = "Arial"

OnRowDataBound = "RowDataBound"

Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" >

<Columns>

<asp:TemplateField>

    <HeaderTemplate>      <asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />

    </HeaderTemplate>

   <ItemTemplate>     <asp:CheckBox ID="CheckBox1" runat="server" onclick = "Check_Click(this)" />

   </ItemTemplate></asp:TemplateField>

<asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID"  />

<asp:BoundField ItemStyle-Width="150px" DataField="City"

HeaderText="City" />

<asp:BoundField ItemStyle-Width="150px" DataField="Country"

HeaderText="Country"/>

<asp:BoundField ItemStyle-Width="150px" DataField="PostalCode"  HeaderText= "PostalCode"/>

</Columns>

</asp:GridView>

Above you will notice I am calling two JavaScript functions checkAll and Check_Click which I have explained later.

Also I have attached a RowDataBound event to the GridView to add mouseover event

Highlight Row when checkbox is checked

<script type = "text/javascript">

function Check_Click(objRef)

{

    //Get the Row based on checkbox    var row = objRef.parentNode.parentNode;

    if(objRef.checked)

    {

        //If checked change color to Aqua        row.style.backgroundColor = "aqua";

Page 34: ASP GridView Practicals

    }

    else    {   

        //If not checked change back to original color        if(row.rowIndex % 2 == 0)

        {

           //Alternating Row Color           row.style.backgroundColor = "#C2D69B";

        }

        else        {

           row.style.backgroundColor = "white";

        }

    }

       //Get the reference of GridView    var GridView = row.parentNode;

   

    //Get all input elements in Gridview    var inputList = GridView.getElementsByTagName("input");

       for (var i=0;i<inputList.length;i++)

    {

        //The First element is the Header Checkbox        var headerCheckBox = inputList[0];

       

        //Based on all or none checkboxes

        //are checked check/uncheck Header Checkbox        var checked = true;

        if(inputList[i].type == "checkbox" && inputList[i] != headerCheckBox)

        {

            if(!inputList[i].checked)

            {

                checked = false;

                break;

            }

        }

    }

    headerCheckBox.checked = checked;

   }

</script>

The above function is invoked when you check / uncheck a checkbox in GridView row

First part of the function highlights the row if the checkbox is checked else it changes the row to the original color if the checkbox is unchecked.

The Second part loops through all the checkboxes to find out whether at least one checkbox is unchecked or not.

Page 35: ASP GridView Practicals

If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it

Check all checkboxes functionality

<script type = "text/javascript">

function checkAll(objRef)

{

    var GridView = objRef.parentNode.parentNode.parentNode;

    var inputList = GridView.getElementsByTagName("input");

    for (var i=0;i<inputList.length;i++)

    {

        //Get the Cell To find out ColumnIndex        var row = inputList[i].parentNode.parentNode;

        if(inputList[i].type == "checkbox"  && objRef != inputList[i])

        {

            if (objRef.checked)

            {

                //If the header checkbox is checked

                //check all checkboxes

                //and highlight all rows                row.style.backgroundColor = "aqua";

                inputList[i].checked=true;

            }

            else            {

                //If the header checkbox is checked

                //uncheck all checkboxes

                //and change rowcolor back to original                if(row.rowIndex % 2 == 0)

                {

                   //Alternating Row Color                   row.style.backgroundColor = "#C2D69B";

                }

                else                {

                   row.style.backgroundColor = "white";

                }

                inputList[i].checked=false;

            }

        }

    }

}

</script> 

The above function is executed when you click the Header check all checkbox When the Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows.

And when unchecked it restores back the original color of the row and unchecks the checkboxes.

 Note:

Page 36: ASP GridView Practicals

The check all checkboxes checks all the checkboxes only for the current page of the GridView and not all.

 Highlight GridView row on mouseover event

<script type = "text/javascript">

function MouseEvents(objRef, evt)

{

    var checkbox = objRef.getElementsByTagName("input")[0];

   if (evt.type == "mouseover")

   {

        objRef.style.backgroundColor = "orange";

   }

   else   {

        if (checkbox.checked)

        {

            objRef.style.backgroundColor = "aqua";

        }

        else if(evt.type == "mouseout")

        {

            if(objRef.rowIndex % 2 == 0)

            {

               //Alternating Row Color               objRef.style.backgroundColor = "#C2D69B";

            }

            else            {

               objRef.style.backgroundColor = "white";

            }

        }

   }

}

</script>

The above JavaScript function accepts the reference of the GridView Row and the event which has triggered it.

Then based on the event type if event is mouseover it highlights the row by changing its color to orange else if the event is mouseout it changes the row’s color back to its original before the event occurred.

The above function is called on the mouseover and mouseout events of the GridView row. These events are attached to the GridView Row on the RowDataBound events refer the code below

protected void RowDataBound(object sender, GridViewRowEventArgs e)

{

    if (e.Row.RowType == DataControlRowType.DataRow )

    {

        e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");

        e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)"); 

Page 37: ASP GridView Practicals

    }

}

o/p

Implement Pagination in ASP.Net Gridview Control

http://www.aspsnippets.com/Articles/Implement-Pagination-in-ASP.Net-Gridview-Control.aspx

The following properties of the GridView come into play when Paging needs to be added.

1. PageSize - Sets the Size of the Page for GridView control

2. PageIndexChanging – The event that will be triggered when the page link is clicked by the user.

 

Below is the markup of the GridView control

<asp:GridView ID="GridView1" runat="server"    AutoGenerateColumns = "false" Font-Names = "Arial"    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"     HeaderStyle-BackColor = "green" AllowPaging ="true"      OnPageIndexChanging = "OnPaging"    PageSize = "10" >   <Columns>    <asp:BoundField ItemStyle-Width = "150px"      DataField = "CustomerID" HeaderText = "CustomerID" />    <asp:BoundField ItemStyle-Width = "150px"      DataField = "City" HeaderText = "City"/>    <asp:BoundField ItemStyle-Width = "150px"      DataField = "Country" HeaderText = "Country"/>    <asp:BoundField ItemStyle-Width = "150px"      DataField = "PostalCode" HeaderText = "PostalCode"/>   </Columns>   <AlternatingRowStyle BackColor="#C2D69B"  /></asp:GridView>  

As you can see above there are four columns in the GridView

1. Customer ID

2. City

Page 38: ASP GridView Practicals

3. Country

4. Postal Code

 Below is the function that will execute the Query and retrieve the records from the database

private DataTable GetData(SqlCommand cmd){    DataTable dt = new DataTable();    String strConnString = System.Configuration.ConfigurationManager        .ConnectionStrings["conString"].ConnectionString;    SqlConnection con = new SqlConnection(strConnString);    SqlDataAdapter sda = new SqlDataAdapter();    cmd.CommandType = CommandType.Text;    cmd.Connection = con;    try    {        con.Open();        sda.SelectCommand = cmd;        sda.Fill(dt);        return dt;    }    catch (Exception ex)    {        throw ex;    }    finally    {        con.Close();        sda.Dispose();        con.Dispose();    }

}

The above function simply executes the query and returns the set of rows in a datatable.

 Finally ,calling the above function in Page Load event of the page and binding the returned dataset to the GridView control

protected void Page_Load(object sender, EventArgs e){    string strQuery = "select CustomerID,City,Country,PostalCode" +        " from customers";    SqlCommand cmd = new SqlCommand(strQuery);    DataTable dt = GetData(cmd);    GridView1.DataSource=dt;    GridView1.DataBind(); 

}

And now in order make the paging functionality work we will need to add the OnPageIndexChanging event of the

GridView control

protected void OnPaging(object sender, GridViewPageEventArgs e){    GridView1.PageIndex = e.NewPageIndex;    GridView1.DataBind();

}

As you can see above I am assigning a new Page index to the GridView and the rebinding the GridView control.

Page 39: ASP GridView Practicals

The figure below displays the GridView with Paging enabled.

Preserving state of Checkboxes while paging in ASP.Net GridView Control

http://www.aspsnippets.com/Articles/Preserving-state-of-Checkboxes-while-paging-in-ASP.Net-GridView-

Control.aspx

To start with I have a GridView as below

<asp:GridView ID="GridView1" runat="server"AutoGenerateColumns = "false" Font-Names = "Arial"Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" HeaderStyle-BackColor = "green" AllowPaging ="true"  OnPageIndexChanging = "OnPaging" OnRowDataBound = "RowDataBound"  PageSize="10"><Columns><asp:TemplateField>    <HeaderTemplate>        <asp:CheckBox ID="chkAll" runat="server"            onclick = "checkAll(this);" />    </HeaderTemplate>    <ItemTemplate>        <asp:CheckBox ID="CheckBox1" runat="server"            onclick = "Check_Click(this)"/>    </ItemTemplate></asp:TemplateField><asp:BoundField ItemStyle-Width = "150px"    DataField = "CustomerID" HeaderText = "CustomerID" /><asp:BoundField ItemStyle-Width = "150px"    DataField = "City" HeaderText = "City"/><asp:BoundField ItemStyle-Width = "150px"    DataField = "Country" HeaderText = "Country"/><asp:BoundField ItemStyle-Width = "150px"    DataField = "PostalCode" HeaderText = "PostalCode"/></Columns></asp:GridView>

 Namespaces

You will need to import the following namespace since I am using ArrayList to store the checked checkboxes

using System.Collections;

Page 40: ASP GridView Practicals

The following code checks if the ViewState has ArrayList Stored in it if yes it gets it from the ViewState else creates a

new ArrayList which will store the selected checkboxes.

ArrayList CheckBoxArray;if (ViewState["CheckBoxArray"] != null){    CheckBoxArray = (ArrayList)ViewState["CheckBoxArray"];}else{    CheckBoxArray = new ArrayList();

}

The next code snippet gets the reference of the header row check all checkbox and checks if the checkbox is

checked or unchecked

If the checkbox is checked it adds its reference in the ArrayList in the format chkAll-0 where 0 is the page index of the

GridView page.

If the checkbox is unchecked it checks whether its reference is present in the ArrayList or not if the reference is

present it removes the reference from the ArrayList and sets the flag CheckAllWasChecked which is useful in the

next snippet.

int CheckBoxIndex;    bool CheckAllWasChecked=false;    CheckBox chkAll =     (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkAll");    string checkAllIndex = "chkAll-" + GridView1.PageIndex;    if (chkAll.Checked)    {        if (CheckBoxArray.IndexOf(checkAllIndex) == -1)        {            CheckBoxArray.Add(checkAllIndex);        }    }    else    {        if (CheckBoxArray.IndexOf(checkAllIndex) != -1)        {            CheckBoxArray.Remove(checkAllIndex);            CheckAllWasChecked = true;        }    }

The next snippet loops through the GridView rows and checks if the checkbox for that corresponding row is checked.

If the checkbox is checked its position is calculated using the following formula

CheckBoxIndex = GridView1.PageSize * GridView1.PageIndex + (RowIndex + 1)

 

The above formula gives the checkbox. RowIndex and PageIndex are zero based indexes i.e the first row or first

page starts from 0.

If the checkbox is checked its CheckBoxIndex added to the ArrayList else if it is already present and the checkbox is

not checked it is removed.

for (int i = 0; i < GridView1.Rows.Count; i++)

Page 41: ASP GridView Practicals

{    if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)    {        CheckBox chk =         (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");        CheckBoxIndex = GridView1.PageSize * GridView1.PageIndex + (i + 1);        if (chk.Checked)        {            if (CheckBoxArray.IndexOf(CheckBoxIndex) == -1                && !CheckAllWasChecked)            {                CheckBoxArray.Add(CheckBoxIndex);            }        }        else        {            if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1                || CheckAllWasChecked)            {                CheckBoxArray.Remove(CheckBoxIndex);            }        }    }

}

The complete snippet is given below.

if (IsPostBack){    int CheckBoxIndex;    bool CheckAllWasChecked=false;    CheckBox chkAll =     (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkAll");    string checkAllIndex = "chkAll-" + GridView1.PageIndex;    if (chkAll.Checked)    {        if (CheckBoxArray.IndexOf(checkAllIndex) == -1)        {            CheckBoxArray.Add(checkAllIndex);        }    }    else    {        if (CheckBoxArray.IndexOf(checkAllIndex) != -1)        {            CheckBoxArray.Remove(checkAllIndex);            CheckAllWasChecked = true;        }    }    for (int i = 0; i < GridView1.Rows.Count; i++)    {        if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)        {          CheckBox chk =          (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");           CheckBoxIndex=GridView1.PageSize*GridView1.PageIndex + (i + 1);          if (chk.Checked)          {

Page 42: ASP GridView Practicals

                if (CheckBoxArray.IndexOf(CheckBoxIndex) == -1                    && !CheckAllWasChecked)                {                    CheckBoxArray.Add(CheckBoxIndex);                }          }          else          {                if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1                    || CheckAllWasChecked)                {                    CheckBoxArray.Remove(CheckBoxIndex);                }          }        }    }}

Once this is done the ArrayList is saved to the ViewState.

ViewState["CheckBoxArray"] = CheckBoxArray;

Now in the GridView Paging Event you will need to recheck the checkboxes that are present in the ArrayList that we

saved in the ViewState. If the Check All checkbox is checked for that page index it will check all the checkboxes.

While checking through the checkboxes it also applies the background color to all checkboxes that are checked.

ArrayList CheckBoxArray = (ArrayList)ViewState["CheckBoxArray"];string checkAllIndex = "chkAll-" + GridView1.PageIndex; if (CheckBoxArray.IndexOf(checkAllIndex) != -1){    CheckBox chkAll =     (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkAll");    chkAll.Checked = true;}for (int i = 0; i < GridView1.Rows.Count; i++){if (GridView1.Rows[i].RowType == DataControlRowType.DataRow){    if (CheckBoxArray.IndexOf(checkAllIndex) != -1)    {        CheckBox chk =         (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");        chk.Checked = true;        GridView1.Rows[i].Attributes.Add("style","background-color:aqua");         }    else    {      int CheckBoxIndex =GridView1.PageSize*(GridView1.PageIndex)+(i + 1);      if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1)      {         CheckBox chk =         (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");        chk.Checked = true;        GridView1.Rows[i].Attributes.Add("style", "background-color:aqua");      }    }}}

Page 43: ASP GridView Practicals

Display sum of columns total in gridview footer in asp.nethttp://www.aspdotnet-suresh.com/2011/02/how-to-display-sum-of-columns-total-in.html

Description:  

I have a one gridview with multiple rows and columns and for that gridview paging also has enabled now my requirement I need to display sum of all the columns (Total) in gridview footer for that I have used gridview row databound condition this functionality will work for paging enabled gridview also. Before proceed to functionality first we need to design one table in database and give name EmployeeSalary  

ColumnName DataTypeEmpID Int(set identity property=true)EmpName varchar(50)Location varchar(50)Amount varchar(50)

After completion table creation enter some dummy and design your aspx page like this

<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="gvEmp" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold ="true" DataKeyNames="EmpID" runat="server"ShowFooter="true" AllowPaging="true" PageSize="5" AutoGenerateColumns="false" DataSourceID="sqldsEmp" onrowdatabound="gvEmp_RowDataBound"><FooterStyle Font-Bold="true" BackColor="#61A6F8" ForeColor="black" /><Columns><asp:BoundField DataField="EmpID" HeaderText="Emp ID" /><asp:BoundField DataField="EmpName" HeaderText="Emp Name" /><asp:TemplateField  HeaderText="Location"><ItemTemplate><asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'/></ItemTemplate><FooterTemplate><asp:Label ID="lbltxttotal" runat="server" Text="Total Amount"/></FooterTemplate></asp:TemplateField><asp:TemplateField HeaderText="Amount"><ItemTemplate><asp:Label ID="lblamount" runat="server" Text='<%# Eval("Amount") %>'/></ItemTemplate><FooterTemplate><asp:Label ID="lblTotal" runat="server" /></FooterTemplate></asp:TemplateField></Columns></asp:GridView><asp:SqlDataSource ID="sqldsEmp" runat="server" SelectCommand="select * from EmployeeSalary"ConnectionString="<%$ ConnectionStrings:dbconnection %>"></asp:SqlDataSource>

Page 44: ASP GridView Practicals

</div></form></body></html> After completion of aspx page write the following code in codebehind

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();}}

After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database

<connectionStrings><add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/></connectionStrings >