Showing posts with label ASP.Net. Show all posts
Showing posts with label ASP.Net. Show all posts

ASP.NET ListBox with Multi Select DropdownList with CheckBoxes Using jQuery

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) with ListBox control using CheckBox in ASP.NET with help of jQuery, Bootstrap and MultiSelect JS.

In ASPX File

In aspx file, create a ListBox control with SelectionMode="Multiple" and bind with some dummy ListItem data as shown below.
Here in script JS files, First is jQuery file and Second, Third is bootstrap JS and CSS files and Fourth and Fifth file is MultiSelect JS and CSS Files.
Make sure all files is loaded when application runs.
Here includeSelectAllOption is set to true to include Select All text at first position in Select List.

Entity Framework CRUD Operations with GridView in ASP.NET

In this tutorial, I am going to explain you CRUD (Create, Read, Update and Delete) operations using Entity Framework with GridView control in ASP.NET. I will be using Visual Studio 2013, SQL-Server 2008R2 and Entity Framework 6.0. Below is the step by step tutorial.

Creating Database Table

We will be using two tables tbl_UserMaster and tbl_Country. tbl_UserMaster table is used to store User Details and tbl_Country table is used to bind country name in DropDownList while adding new record and editing existing record.

UserMaster and Country Table
Creating table

Below is the script to create tables and add dummy data into it.

ASP.NET MVC WebGrid Paging, Sorting and showing loading or progress image using Entity Framework

In this article, I am going to explain you ASP.NET MVC WebGrid paging, Sorting and display progress bar or loading image while paging or sorting WebGrid. We will be using visual studio 2013, sql server 2008 r2 and entity framework 6.0.

This article is extension to previous one. In the previous article, we used Dapper ORM to load data but in this demo we will use Entity Framework 6.0 to load record from database and to delete record using checkbox and delete button. Below is the link.
WebGrid Demo
Below is step by step tutorial.

Creating table

Below is the scripts to create a tbl_Employee table and add some dummy data.

Generate Pay slip / Salary slip PDF using iTextSharp in ASP.NET

In this article, I am going to explain you how to generate employee pay slip or salary slip in PDF format using itextsharp in asp.net . I will be using visual studio 2013 professional. Before continuing this article, let's see the screen-shots.

When the page is loaded for the first time then you will see the below screen. You will select employee id and month and click on generate button to download salary slip. I have hard-coded some employee id and month in dropdownlist control in aspx file.

Generate salary slip using itextsharp in asp.net

I have shared pdf file sample as shown below in iframe.

So, below is the step by step tutorial.

Creating table and procedure

Below is the scripts to create 2 tables tbl_EmployeeDetails and tbl_SalaryDetails for employee details and salary details.

Export DataTable to PDF file using iTextSharp and download/transmit at client machine

In this article, I am going to explain you how to export DataTable to PDF file using iTextSharp in C# and download or transmit at client machine. First, you need to download iTextSharp dll from the internet. Click on the below link to download the dll.
https://github.com/itext/itextsharp

Once file is downloaded, extract it, now you will find 6 more .rar file. Again extract itextsharp-dll-core.rar file, after that add reference of itextsharp.dll to your project.

Related Article

  1. How to export GridView data into PDF using iTextSharp in asp.net with C#
  2. Insert an image into PDF using iTextSharp with C# (C-Sharp)
  3. How to add meta information of PDF file using iTextSharp with C-Sharp
  4. How to extract images from a pdf file using C#.Net

In Code-Behind File

Add below nampespaces.

using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;

C# Code Snippet

Below is complete C# code to generate pdf file using dummy data table.

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

private void ExportDataTableToPdfandDownloadAtClient()
{
    // creating datatable and adding dumy data
    DataTable dtEmployee = new DataTable();
    dtEmployee.Columns.Add("EmpId", typeof(Int32));
    dtEmployee.Columns.Add("Name", typeof(string));
    dtEmployee.Columns.Add("Gender", typeof(string));
    dtEmployee.Columns.Add("Salary", typeof(Int32));
    dtEmployee.Columns.Add("Country", typeof(string));
    dtEmployee.Rows.Add(1, "Rahul", "Male", 60000, "India");
    dtEmployee.Rows.Add(2, "John", "Male", 50000, "USA");
    dtEmployee.Rows.Add(3, "Mary", "Female", 75000, "UK");
    dtEmployee.Rows.Add(4, "Mathew", "Male", 80000, "Australia");

    // creating document object
    iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4);
    rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive);
    Document doc = new Document(rec);
    doc.SetPageSize(iTextSharp.text.PageSize.A4);
    PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
    doc.Open();

    //Creating paragraph for header
    BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.ORANGE);
    Paragraph prgHeading = new Paragraph();
    prgHeading.Alignment = Element.ALIGN_LEFT;
    prgHeading.Add(new Chunk("Employee Details".ToUpper(), fntHead));
    doc.Add(prgHeading);

    //Adding paragraph for report generated by
    Paragraph prgGeneratedBY = new Paragraph();
    BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLUE);
    prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;
    prgGeneratedBY.Add(new Chunk("Report Generated by : ASPArticles", fntAuthor));
    prgGeneratedBY.Add(new Chunk("\nGenerated Date : " + DateTime.Now.ToShortDateString(), fntAuthor));
    doc.Add(prgGeneratedBY);

    //Adding a line
    Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
    doc.Add(p);

    //Adding line break
    doc.Add(new Chunk("\n", fntHead));

    //Adding  PdfPTable
    PdfPTable table = new PdfPTable(dtEmployee.Columns.Count);

    for (int i = 0; i < dtEmployee.Columns.Count; i++)
    {
        string cellText = Server.HtmlDecode(dtEmployee.Columns[i].ColumnName);
        PdfPCell cell = new PdfPCell();
        cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ffffff"))));
        cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#990000"));
        //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.HeaderStyle.ForeColor)));
        //cell.BackgroundColor = new BaseColor(grdStudent.HeaderStyle.BackColor);
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.PaddingBottom = 5;
        table.AddCell(cell);
    }

    //writing table Data
    for (int i = 0; i < dtEmployee.Rows.Count; i++)
    {
        for (int j = 0; j < dtEmployee.Columns.Count; j++)
        {
            table.AddCell(dtEmployee.Rows[i][j].ToString());
        }
    }

    doc.Add(table);
    doc.Close();
    writer.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;" + "filename=EmployeeDetails.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(doc);
    Response.End();
}

Below is the pdf file will be downloaded at client machine.

Export datatable to pdf file using itextsharp


DOWNLOAD SOURCE CODE

Check uncheck or select deselect CheckBox using jQuery with GridView in ASP.NET

In this article, I am going to explain you, how to check and uncheck all checkboxes using jQuery in asp.net gridview. If header row checkbox is checked then all row checboxes should be checked and if any of row checkbox is unchecked then header checkbox should be unchecked.

DOWNLOAD SOURCE CODE
check uncheck or select deselect all checkboxes using jQuery
check uncheck or selectde select all checkboxes using jQuery in gridview

Data Source

To bind gridview, we need to have some dummy data. Below is the script to create table and insert data into it. Script is attached inside download source code folder.

create table tblStudent
(
Id int primary key identity,
Name varchar(50),
Gender varchar(10),
Marks int,
City varchar(50)
)
go
insert into tblStudent values('Rahul', 'Male', 10, 'Mumbai')
insert into tblStudent values('John','Male', 15,'London')
insert into tblStudent values('Mathew','Male', 20,'Sydney')
insert into tblStudent values('Mary','Female', 25,'Delhi')
insert into tblStudent values('Mithum','Male', 30,'Delhi')
insert into tblStudent values('Sara','Female', 35,'London')
insert into tblStudent values('Rahul','Male', 40,'Mumbai')
insert into tblStudent values('John','Male', 45,'London')
insert into tblStudent values('Mathew','Male', 50,'Sydney')
insert into tblStudent values('Mary','Female', 55,'Delhi')
insert into tblStudent values('Mithum','Male', 60,'Delhi')
insert into tblStudent values('Sara','Female', 65,'London')
insert into tblStudent values('Rahul','Male', 70,'Mumbai')
insert into tblStudent values('John','Male', 75,'London')
insert into tblStudent values('Mathew','Male', 80,'Sydney')
insert into tblStudent values('Mary','Female', 85,'Delhi')
insert into tblStudent values('Mithum','Male', 90,'Delhi')

Design GridView

In aspx file, create a gridview control as shown below. In the first TemplateField, there are two check-boxes chkHead and chkRow.

<div style="margin-top: 25px; margin-left: 250px;">
    <asp:GridView ID="grdStudent" runat="server" DataKeyNames="Id" CellPadding="5" 
       AutoGenerateColumns="false" Width="540px" OnPageIndexChanging="grdStudent_PageIndexChanged" 
       AllowPaging="true" PageSize="5">
        <AlternatingRowStyle BackColor="White" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <RowStyle HorizontalAlign="Center" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Left" />
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkHead" runat="server"></asp:CheckBox>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Gender">
                <ItemTemplate>
                    <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Marks">
                <ItemTemplate>
                    <asp:Label ID="lblMarks" runat="server" Text='<%#Eval("Marks") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code-Behind File

In code-behind file, bind gridview control using dummy data from database as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;//namespace added
using System.Configuration;//namespace added
using System.Data.SqlClient;//namespace added

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

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

        private void BindGrid()
        {
            DataSet ds = null;
            SqlConnection con = null;
            try
            {
                con = new SqlConnection(ConnString);
                SqlCommand cmd = new SqlCommand("select * from tblStudent", con);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                ds = new DataSet();
                sda.Fill(ds);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    grdStudent.DataSource = ds.Tables[0];
                    grdStudent.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    grdStudent.DataSource = ds;
                    grdStudent.DataBind();
                    grdStudent.Rows[0].Visible = false;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }

        protected void grdStudent_PageIndexChanged(object sender, GridViewPageEventArgs e)
        {
            grdStudent.PageIndex = e.NewPageIndex;
            BindGrid();
        }
    }
}

jQuery Code

First we need to add jQuery file to our application. We can either download latest jQuery file from http://jquery.com/download/ and put jQuery file into Script folder of our application or we can directly use CDN links in code as shown below.
Code to load jQuery Framework from Google CDN

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>

I am using downloaded jQuery file as shown below and below is the complete jQuery code to select and deselect check-boxes.

<head runat="server">
  <title></title>
  <script src="Scripts/jquery-3.0.0.js" type="text/javascript"></script>
  
  <script type="text/javascript" language="javascript">
    $(document).ready(function () {

      //this code will be executed on click of header row checkbox
      $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").click(function () {

        //check if header row checkbox is checked and store into variable
        var flag = $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").is(':checked');

        //find all row checkboxes: if flag == true then set attribute checked=true or if flag == false then set checked=false
        $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").prop('checked', flag);

      });

      //this code will be executed on click of data row checkbox
      $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").click(function () {

        //count total number of row checkboxes
        var rowCheckboxesCount = $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").length;

        //count total number of row checkboxes which are checked
        var rowCheckboxesCheckedCount = $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox:checked").length;

        // if counts are same that means:  total number of row checkboxes == total number of row checkboxes which are checked
        // then find header row checkbox and set to true or false
        $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").prop('checked', rowCheckboxesCount == rowCheckboxesCheckedCount);

      });

    });
  </script>
</head>

Delete selected (multiple) rows from GridView using CheckBox with JavaScript confirmation

In this article, I am going to explain you, how to delete multiple records or selected records from GridView control using CheckBox with JavaScript delete confirmation box.

DOWNLOAD SOURCE CODE

Below is the gridview look like when it is binded and alert will be shown when user try to delete the records. Main purpose in this article is to show the delete confirmation box before deleting and delete selected records.

Delete selected records using javascript confirmation box

When a user selects record and click on Delete Selected Records button then a javascript confirmation box will be shown to user whether 'they want to delete select records' and form will be posted to server if click on OK. In this demo, confirmation box is shown whether user selects or doesn't selects any record that means confirmation box will shown to user irrespective of user select or doesn't select any record. I will correct this error in later article.

Delete selected record when checkbox is checked

When user clicks on Delete All button then javascript confirmation box will be shown to user whether 'they want to delete all the records' and all the record will be deleted from current page.

Delete all the records

Data Source

To bind gridview, we need to have some dummy data. Below is the script to create table and insert data into it. Script is attached inside download source code folder.

create table tblStudent
(
Id int primary key identity,
Name varchar(50),
Gender varchar(10),
Marks int,
City varchar(50)
)
go
insert into tblStudent values('Rahul', 'Male', 10, 'Mumbai')
insert into tblStudent values('John','Male', 15,'London')
insert into tblStudent values('Mathew','Male', 20,'Sydney')
insert into tblStudent values('Mary','Female', 25,'Delhi')
insert into tblStudent values('Mithum','Male', 30,'Delhi')
insert into tblStudent values('Sara','Female', 35,'London')
insert into tblStudent values('Rahul','Male', 40,'Mumbai')
insert into tblStudent values('John','Male', 45,'London')
insert into tblStudent values('Mathew','Male', 50,'Sydney')
insert into tblStudent values('Mary','Female', 55,'Delhi')
insert into tblStudent values('Mithum','Male', 60,'Delhi')
insert into tblStudent values('Sara','Female', 65,'London')
insert into tblStudent values('Rahul','Male', 70,'Mumbai')
insert into tblStudent values('John','Male', 75,'London')
insert into tblStudent values('Mathew','Male', 80,'Sydney')
insert into tblStudent values('Mary','Female', 85,'Delhi')
insert into tblStudent values('Mithum','Male', 90,'Delhi')

In Designer File

Create a GridView control with 5 TemplateField. In the first TemplateField, create a LinkButton control inside HeaderTemplate and CheckBox control inside ItemTemplate. On click on LinkButton a JavaScript function DeleteAll will be called which returns true or false accordingly. Create a Button control outside of GridView to delete selected record. On click of delete button, JavaScript function DeleteSelected will be called which also returns true or false accordingly. Below is the complete designer file code with JavaScript functions and to give GridView nicer look, I have used css for header row, footer row and pager row.

Below is the JavaScript and CSS code.

    <script type="text/javascript">
        function DeleteAll() {
            var result = confirm('Are you sure you want to delete all the records?');
            if (result) {
                return true;
            }
            else {
                return false;
            }
        }
        function DeleteSelected() {
            var result = confirm('Are you sure you want to delete selected records?');
            if (result) {
                return true;
            }
            else {
                return false;
            }
        }
    </script>
    <style type="text/css">
        .grdStudentPager {
            background-color: #594c2d;
            color: White;
            padding: 2px;
            margin: 2% auto;
            horizontalalign: left;
        }

            .grdStudentPager a {
                margin: auto 1%;
                border-radius: 50%;
                background-color: #444;
                padding: 5px 10px 5px 10px;
                color: #fff;
                text-decoration: none;
                -o-box-shadow: 1px 1px 1px #111;
                -moz-box-shadow: 1px 1px 1px #111;
                -webkit-box-shadow: 1px 1px 1px #111;
                box-shadow: 1px 1px 1px #111;
            }

                .grdStudentPager a:hover {
                    background-color: #329bd8;
                    color: #fff;
                }

            .grdStudentPager span {
                background-color: #FFFFCC;
                color: Black;
                -o-box-shadow: 1px 1px 1px #111;
                -moz-box-shadow: 1px 1px 1px #111;
                -webkit-box-shadow: 1px 1px 1px #111;
                box-shadow: 1px 1px 1px #111;
                border-radius: 50%;
                padding: 5px 10px 5px 10px;
            }
    </style>

Below is the complete GridView design code.

<div style="margin-top: 25px; margin-left: 250px;">
    <table>
        <tr>
            <td>
                <asp:GridView ID="grdStudent" runat="server" DataKeyNames="Id" CellPadding="5" BackColor="#FFFFCC"
                    AutoGenerateColumns="false" Width="540px" OnPageIndexChanging="grdStudent_PageIndexChanged"
                    AllowPaging="true" PageSize="5" 
                    Style="box-shadow: inset 0 0 10px #000000; -webkit-box-shadow: inset 0 0 10px #000000;
                    -moz-box-shadow: inset 0 0 10px #000000;">
                    <HeaderStyle BackColor="#594c2d" Font-Bold="true" ForeColor="White" />
                    <PagerStyle CssClass="grdStudentPager" />
                    <RowStyle HorizontalAlign="Center" />
                    <Columns>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                <asp:LinkButton ID="btnDeleteAll" runat="server" Text="Delete All" ForeColor="White"
                                    OnClick="btnDeleteAll_Click" OnClientClick="return DeleteAll();">
                                </asp:LinkButton>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Gender">
                            <ItemTemplate>
                                <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Marks">
                            <ItemTemplate>
                                <asp:Label ID="lblMarks" runat="server" Text='<%#Eval("Marks") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="City">
                            <ItemTemplate>
                                <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnDeleteSelected" runat="server" Text="Delete Selected Records"
                    OnClick="btnDeleteSelected_Click" OnClientClick="return DeleteSelected();"
                    Style="color: White; font-size: 12px; font-weight: bold; background-color: #594c2d; 
                    height: 40px; border-radius: 0.5em; padding: 7px; text-transform: uppercase;" />
            </td>
        </tr>
    </table>
</div>

In C# Code-Behind File

Below is the namespace required.

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

Below is the complete C# code to load gridview and to delete record.

// retrieve connection string from web.config file
string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

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

private void BindGrid()
{
    DataSet ds = null;
    SqlConnection con = null;
    try
    {
        con = new SqlConnection(ConnString);
        SqlCommand cmd = new SqlCommand("select * from tblStudent", con);
        cmd.CommandType = CommandType.Text;
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        ds = new DataSet();
        sda.Fill(ds);

        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            grdStudent.DataSource = ds.Tables[0];
            grdStudent.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            grdStudent.DataSource = ds;
            grdStudent.DataBind();
            grdStudent.Rows[0].Visible = false;
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }
}

protected void grdStudent_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
    try
    {
        grdStudent.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    catch (Exception ex)
    {

    }
}

protected void btnDeleteSelected_Click(object sender, EventArgs e)
{
    try
    {
        foreach (GridViewRow gvrow in grdStudent.Rows)
        {
            CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
            if (chkRow != null && chkRow.Checked)
            {
                string id = Convert.ToString(grdStudent.DataKeys[gvrow.RowIndex].Values["Id"]);
                if (!string.IsNullOrEmpty(id))
                {
                    DeleteRecord(id);
                }
            }
        }
        BindGrid();
    }
    catch (Exception ex)
    {

    }
}

protected void btnDeleteAll_Click(object sender, EventArgs e)
{
    try
    {
        foreach (GridViewRow gvrow in grdStudent.Rows)
        {
            if (gvrow.RowType == DataControlRowType.DataRow)
            {
                string id = Convert.ToString(grdStudent.DataKeys[gvrow.RowIndex].Values["Id"]);
                if (!string.IsNullOrEmpty(id))
                {
                    DeleteRecord(id);
                }
            }
        }
        BindGrid();
    }
    catch (Exception ex)
    {

    }
}

private void DeleteRecord(string id)
{
    SqlConnection con = null;
    try
    {
        con = new SqlConnection(ConnString);
        SqlCommand cmd = new SqlCommand("delete from tblStudent where Id=" + Convert.ToInt32(id), con);
        cmd.CommandType = CommandType.Text;
        con.Open();
        int count = cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
    }
}

Check/uncheck or select/deselect all CheckBoxes using JavaScript in ASP.NET GridView

In this article, I am going to explain you, how to check and uncheck all checkboxes in asp.net gridview. If header row checkbox is checked then all row checboxes should be checked and if any of row checkbox is unchecked then header checkbox should be unchecked.

DOWNLOAD SOURCE CODE
check uncheck or select deselect all checkboxes using javascript
check uncheck or selectde select all checkboxes using javascript in gridview

Design GridView

In aspx file, create a gridview control as shown below and its contains 4 columns. First column contains header and row checkboxes. We are calling javascript funcion on click of header and row checkboxes.

<div align="center" style="margin-top: 30px;">
    <asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="false" Width="600px"
        AllowPaging="true" PageSize="5" OnPageIndexChanging="gvStudent_PageIndexChanging" CssClass="Grid"
        AlternatingRowStyle-CssClass="alt"
        PagerStyle-CssClass="pgr">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkHead" runat="server" onclick="chkHeadClick(this);">
                    </asp:CheckBox>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server" onclick="chkRowClick(this);" Style="text-align: center;">
                    </asp:CheckBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student Id">
                <ItemTemplate>
                    <asp:Label ID="lblStudentId" runat="server" Text='<%#Eval("Id") %>'>
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student Name">
                <ItemTemplate>
                    <asp:Label ID="lblStudentName" runat="server" Text='<%#Eval("Name") %>'>
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Student Subject">
                <ItemTemplate>
                    <asp:Label ID="lblStudentSubject" runat="server" Text='<%#Eval("Subject") %>'>
                    </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code-Behind File

In code-behind file, bind gridview control using dummy data as shown below.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
  public partial class WebForm1 : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if(!IsPostBack)
      {
          LoadStudentGrid();
      }
    }
    private void LoadStudentGrid()
    {
      //Creating DataTable of Student
      DataTable dt = new DataTable();
      //adding Columns to DataTable
      dt.Columns.Add("Id", typeof(Int32));
      dt.Columns.Add("Name", typeof(string));
      dt.Columns.Add("Subject", typeof(string));
      //adding Rows to DataTable
      dt.Rows.Add(1, "Rahul", "Maths");
      dt.Rows.Add(2, "Sachin", "Physics");
      dt.Rows.Add(3, "Yogesh", "Chemistry");
      dt.Rows.Add(2, "Sharad", "Economics");
      dt.Rows.Add(4, "Deepak", "Chemistry");
      dt.Rows.Add(5, "Savio", "Economics");
      dt.Rows.Add(6, "Sumit", "Physics");
      dt.Rows.Add(7, "Ram", "Chemistry");
      gvStudent.DataSource = dt;
      gvStudent.DataBind();
    }
    protected void gvStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
      gvStudent.PageIndex = e.NewPageIndex;
      LoadStudentGrid();
    }
  }
}

JavaScript and CSS Code

Below is javascript and css file code. Write it in head tag.

<script type="text/javascript">

    // on header checkbox click 
    function chkHeadClick(checkbox) {
        // find out gridview
        var grid = document.getElementById("gvStudent");

        for (var i = 1; i < grid.rows.length; i++) {
            // iterating from row checkbox and set checked to true
            var inputs = grid.rows[i].cells[0].getElementsByTagName("INPUT");
            for (var j = 0; j < inputs.length; j++) {
                // check if inputs is of type checkbox
                if (inputs[j].getAttribute('type') == 'checkbox') {
                    grid.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = checkbox.checked;
                }
            }

        }

    }

    // on row checkbox click
    function chkRowClick(checkbox) {

        // find out gridview
        var grid = document.getElementById("gvStudent");

        var rowUncheckFlag = false;

        // count total number of row including header row, item row and pager row
        for (var i = 1; i < grid.rows.length; i++) {

            // start from item row [i=1] excluding header row[i=0] checkbox
            var inputs = grid.rows[i].cells[0].getElementsByTagName("INPUT");

            for (var j = 0; j < inputs.length; j++) {
                // check if inputs is of type checkbox
                if (inputs[j].getAttribute('type') == 'checkbox') {

                    if (grid.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false) {
                        rowUncheckFlag = true; // if any of row checkbox is unchecked then set rowUncheckFlag to true
                        break;
                    }
                }
            }
        }

        if (rowUncheckFlag) // if any checkbox is unchecked then make header check box unchecked
        {
            // here rows[0] means first row i.e header check box
            grid.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = false;
        }
        else {
            grid.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = true;
        }
    }
</script>

You can download background image files from Here.

<style type="text/css">
    .Grid {
        background-color: #fff;
        margin: 5px 0 10px 0;
        border: solid 1px #525252;
        border-collapse: collapse;
        font-family: Calibri;
        color: #474747;
    }
    .Grid td {
        padding: 2px;
        border: solid 1px #c1c1c1;
    }
    .Grid th {
        padding: 4px 2px;
        color: #fff;
        background: #363670 url(Images/grid-header.png) repeat-x top;
        border-left: solid 1px #525252;
        font-size: 0.9em;
    }
    .Grid .alt {
        background: #fcfcfc url(Images/grid-alt.png) repeat-x top;
    }
    .Grid .pgr {
        background: #363670 url(Images/grid-pgr.png) repeat-x top;
    }

    .Grid .pgr table {
        margin: 3px 0;
    }
    .Grid .pgr td {
        border-width: 0;
        padding: 0 6px;
        border-left: solid 1px #666;
        font-weight: bold;
        color: #fff;
        line-height: 12px;
    }
    .Grid .pgr a {
        color: Gray;
        text-decoration: none;
    }
    .Grid .pgr a:hover {
        color: #000;
        text-decoration: none;
    }
</style>

ASP.Net Query String to pass data from one page (WebForm) to another page

In this article, we are going to learn how to pass data from one page (aspx page) to another page using Query String in ASP.Net. There are different types of technique available in ASP.Net to pass data from one webform to another webform. Below is the list.
1. Query String (We will discuss in this article)
2. Cross Page Postback (We will discuss in later article)
3. Context.Handler object We will discuss in later article)

Let's understand Query String with an example. First create two webforms i.e. WebForm1.aspx and WebForm2.aspx. In the first webform create two TextBox controls to capture First Name and Last Name and one Button control to send data from WebForm1.aspx to WebForm2.aspx. Below is the designer for first page.

<table>
   <tr>
      <td>FirstName</td>
      <td><asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
   </tr>
   <tr>
      <td>LastName</td>
      <td><asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
   </tr>
   <tr>
      <td colspan="2">
       <asp:Button id="btnSend" runat="server" Text="Send Data" OnClick="btnSend_Click"/>
      </td>
   </tr>
</table>

Now, in the second webform create two Label controls to display First Name and Last Name. Below is the designer for second page.

<table>
   <tr>
      <td>FirstName: </td>
      <td><asp:Label ID="lblFirstName" runat="server"></asp:Label></td>
   </tr>
   <tr>
      <td>LastName: </td>
      <td><asp:Label ID="lblLastName" runat="server"></asp:Label></td>
   </tr>
</table>

Now, we will pass data from webform1 to webform2 onclick on Send Button. As you can see in below code, to pass data we need to append ?(question mark) after the destination url i.e. WebForm2.aspx and after ?(question mark) append key and its value. If you want to pass more than one key/value pair then use & (ampersand) as shown below.

// In webform1.aspx.cs
protected void btnSend_Click(object sender, EventArgs e)
{
   Response.Redirect("~/WebForm2.aspx?FirstName=" +txtFirstName.Text+ "&LastName=" + txtLastName.Text);
}

Now on click of submit button, data will be passed to WebForm2.aspx. To retrieve data from URL, use below code in WebForm2.

// In webform2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
   lblFirstName.Text=Request.QueryString["FirstName"];
   lblLastName.Text = Request.QueryString["LastName"];

   // or you can specify index position
  // lblFirstName.Text = Request.QueryString[0];
  // lblLastName.Text = Request.QueryString[1];
}

You can see in below figure we have passed two key/value pair i.e FirstName and LastName. Data is passed trough the url.

Query String before passing data
Query String after passing data

In above example, we have passed FirstName as 'Sachin' and LastName as 'Tendulkar' and we were able to retrieve the values correctly. Now pass FirstName as 'Sachin & Rahul' and LastName as 'Tendulkar'. Here we got FirstName as 'Sachin' and LastName as 'Tendulkar' because we have used & (ampersand) in first TextBox. You can see in second image, url that formed is containing & (ampersand) two times. So FirstName will be retrieved as 'FirstName=Sachin%20' , here %20 is the space and LastName as 'LastName=Tendulkar' but our requirement is correctly retrieve first parameter as 'Sachin & Rahul'.

Query String with special symbol
Query String with special symbol output

To correct problem with &(ampersand), we can Encode the URL as shown below.

protected void btnSend_Click(object sender, EventArgs e)
{
    Response.Redirect("~/WebForm2.aspx?FirstName=" +
        Server.UrlEncode(txtFirstName.Text) + "&LastName=" + Server.UrlEncode(txtLastName.Text));
}

Now you can see in below figure. %20 is replaced by +(plus) and &(ampersand) is replaced by %26 using UrlEncode. Here we are able to retrieve values correctly.

Query String with url encode

We can use following code to retrieve the parameters.

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < Request.QueryString.Count; i++)
    {
        string Result = Request.QueryString[i];
    }
  
  // you can check null condition also
    if (!string.IsNullOrEmpty(Request.QueryString["FirstName"]))
    {
        lblFirstName.Text = Request.QueryString["FirstName"];
    }
}

More About Query Strings

1. Query strings are common way to send data from one page to another page.
2. Query strings are name/value collection pairs.
3. Query strings are appended to the page url.
4. ?(question mark), indicates the beginning of a query string and it's value.
5. It is possible to use more than one query string. The first query string is specified using the ?(question mark). Subsequent query strings can be appended to the URL using the &(ampersand) symbol.
6. To read the query string value, use Request object's QueryString property.

Disadvantages of Query Strings

1. There is a limit on the Query string length. Hence, Query strings cannot be used to send very long data.
2. Query strings are visible to the user, it should not be used to send sensitive information, unless it is encrypted.