Showing posts with label CheckBox. Show all posts
Showing posts with label CheckBox. Show all posts

Sunday, 10 December 2017

Grid.MVC with MultiSelect DropDownList with CheckBox auto selected from database in MVC

In this tutorial, I am going to explain you bind how to bind multiple selection (MultiSelect) DropDownList with CheckBox in Grid.MVC in ASP.Net MVC from database using jQuery, Bootstrap and MultiSelect JS. I will be using Visual Studio 2013 and ADO.Net code to get data from SQL-Server Database.

As you can see in below screen-shot, multi-select dropdownlist is auto-selected. Here in Subject column , subject value is concatenated with comma from database, while binding to MVCGrid subject is auto selected in last column as shown below.

Grid.MVC with MultiSelect DropDownList with CheckBox auto selected from database in MVC

Creating Table and Procedure

Use below script to create a Student Table and procedure to fetch data from database.

Share:

Sunday, 22 October 2017

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.

Share:

Saturday, 21 October 2017

MVC MultiSelect (Multiple Selection) DropdownList with CheckBoxes Using jQuery

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) DropDownList with CheckBox in MVC using jQuery, Bootstrap and MultiSelect JS.

Creating MVC Model

First of all, we need to create model. Write click on Models folder and add a new class name as CountryModel. Replace all code with below code. CountryList property is used to store List of Country and SelCountry property is used to store selected country while passing to the controller.

Share:

Saturday, 30 September 2017

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.

Share:

Saturday, 16 September 2017

Delete multiple record from WebGrid in ASP.NET MVC using CheckBox

In this article, I am going to explain you how to delete multiple records from ASP.NET MVC WebGrid with the help of CheckBox and Delete button. In this tutorial, we will be discussing only deleting the records. Insert and update will discuss in later tutorials.

I am using visual studio 2013 ultimate, SQL-Server database and Dapper Micro ORM to map database tables to model entity. Below is step by step tutorial.

Creating Database Table

Below is script to create database table and insert some dummy records.

CREATE TABLE tbl_Employee
(
EmpID INT PRIMARY KEY IDENTITY,
Name VARCHAR(100),
Salary INT,
City VARCHAR(50),
Country VARCHAR(50)
)
GO
INSERT INTO tbl_Employee VALUES('Rahul',10000,'Mumbai','India')
INSERT INTO tbl_Employee VALUES('Deepak',15200,'Mumbai','India')
INSERT INTO tbl_Employee VALUES('Savio',15000,'Delhi','India')
INSERT INTO tbl_Employee VALUES('Yogesh',10500,'Mumbai','India')
INSERT INTO tbl_Employee VALUES('Sachin',17000,'Chennai','India')
INSERT INTO tbl_Employee VALUES('Ponting',80000,'Sydney','Australia')
INSERT INTO tbl_Employee VALUES('Josh',24463,'Perth','Australia')
INSERT INTO tbl_Employee VALUES('Johnson',24562,'Melbourne','Australia')
INSERT INTO tbl_Employee VALUES('Gimmy',32456,'Perth','Australia')
INSERT INTO tbl_Employee VALUES('Rex',68355,'Sydney','Australia')
INSERT INTO tbl_Employee VALUES('Rick',99999,'New York','USA')
INSERT INTO tbl_Employee VALUES('Savy',15465,'Chicago','USA')
INSERT INTO tbl_Employee VALUES('Todd',24562,'New York','USA')
INSERT INTO tbl_Employee VALUES('Mary',35485,'New York','USA')
INSERT INTO tbl_Employee VALUES('Mike',15245,'Chicago','USA')

Creating ASP.NET MVC Project

Next step is to create asp.net mvc project.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 folder structure

Installing Dapper Micro-ORM

Next step is to install Dapper Micro-ORM. Right click on References and go to Manage NuGet Packages as shown below.

Adding Dapper ORM using NuGet Packages

After that a new window will open as shown below. Search for Dapper ORM and install it.

Installing dapper orm

Creating Model

Now add a class file Employee.cs in Models folder. Add below properties to Employee class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace WebGridDemo.Models
{
    public class Employee
    {
        public int EmpID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }
}

Now add a New Folder and rename as Repository to root directory of application. Add a class file EmployeeMaster.cs inside Repository folder. Create two methods GetAllEmployees and DeleteRecords inside EmployeeMaster class. GetAllEmployees method executes stored a procedure which returns IEnumerable of type Employee. DeleteRecords method uses in-line query to delete record by using EmpID.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;// add namespance
using WebGridDemo.Models;// add namespance
using System.Data.SqlClient;// add namespance
using System.Configuration;// add namespance
using System.Data; // add namespance

namespace WebGridDemo.Repository
{
  public class EmployeeMaster
  {
    public IEnumerable<Employee> GetAllEmployees()
    {
       //using stored procedure to fetch all the records
       using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
       {
         try
         {
             var emp_list = con.Query<Employee>("usp_GetEmployeeDetails", null, null, true, 0, CommandType.StoredProcedure);
             return emp_list;
         }
         catch
         {
             return null;
         }
       }
    }
    public void DeleteRecords(int id)
    {
       //using inline sql query to delete records
       using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
       {
         try
         {
             string query = "delete from tbl_Employee where EmpID=@EmpID";
             var abc = con.Execute(query, new { EmpID = id });
         }
         catch
         {
             //return null;
         }
       }
    }
  }
}

Below is the script for stored procedure to fetch data.

CREATE proc usp_GetEmployeeDetails
AS
BEGIN
 SELECT * FROM tbl_Employee
END

Adding Controller

Next step is to add controller to application. Add a new empty controller class named as HomeController and add two action methods as shown below. Index method is used to return list of employee to the Index view and DeleteRecords is post method used to delete the records.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebGridDemo.Models;// add namespace
using WebGridDemo.Repository; // add namespace

namespace WebGridDemo.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            EmployeeMaster obj = new EmployeeMaster();
            List<Employee> emplist = new List<Employee>();
            emplist = obj.GetAllEmployees().ToList();
            return View(emplist);
        }

        [HttpPost]
        public ActionResult DeleteRecords(string[] EmpIDs)
        {
            if (EmpIDs != null && EmpIDs.Length > 0)
            {
                foreach (var id in EmpIDs)
                {
                    EmployeeMaster obj = new EmployeeMaster();
                    obj.DeleteRecords(Convert.ToInt32(id));
                }
            }
            return RedirectToAction("Index");
        }
    }
}

Adding View

Next step is to add view. Right click inside index action method and add a new view named as Index and select empty model and add a View. Now open Index.cshtml view which is created inside Views/Home folder. Replace all code with below code.

@model IEnumerable<WebGridDemo.Models.Employee>

@{
    ViewBag.Title = "WebGrid Demo";
    var grid = new WebGrid(canSort: true, rowsPerPage: 5);
    grid.Bind(source: Model);
}

<style>
    .header_style {
        background-color: #055897;
        color: #ffffff;
    }

        .header_style a {
            color: #ffffff !important;
        }

    .table-pager > td {
        padding-top: 10px;
    }

        .table-pager > td > a {
            background-color: #f5f5f5;
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 3px 7px;
        }

            .table-pager > td > a:hover {
                background-color: #f0f0f0;
            }

    .webgrid-alternating-row {
        background-color: #EAF2D3;
        padding: 3px 7px 2px;
    }
</style>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js" type="text/javascript"></script>

<h3 class="text-info">Delete Multiple Reords in WebGrid in MVC</h3>

<div class="test" style="overflow: scroll; width: auto;">
    <div style="width: auto">
        @using (Html.BeginForm("DeleteRecords", "Home", FormMethod.Post))
        {
            if (Model.Count() > 0)
            {
                @grid.GetHtml(
                tableStyle: "table table-responsive table-bordered",
                headerStyle: "header_style",
                rowStyle: "odd",
                alternatingRowStyle: "webgrid-alternating-row",
                footerStyle: "table-pager",
                firstText: "First",
                lastText: "Last",
                nextText: "Next",
                previousText: "Previous",
                columns: grid.Columns
                (
                grid.Column(format: @<text><input type="checkbox" name="EmpIDs" value="@item.EmpId" /></text>, header: "Select"),
                grid.Column("EmpId", "Employee ID"),
                grid.Column("Name", "Employee Name"),
                grid.Column("Salary", "Salary"),
                grid.Column("City", "City"),
                grid.Column("Country", "Country"),
                grid.Column(
                 "Action", format: (item) =>
                 {
                     var links =
                     Html.ActionLink("  ", "Edit", "Product", new { id = item.EmpID }, new { @class = "btn btn-default glyphicon glyphicon-edit" }).ToHtmlString() +
                     Html.ActionLink("  ", "Delete", "Product", new { }, new { @class = "btn btn-default glyphicon glyphicon-remove delete-product", @data_id = item.EmpID }).ToHtmlString();

                     return Html.Raw(links);
                 }
                 , canSort: false)
              ),
mode: WebGridPagerModes.All
)
                <input type="submit" class="btn btn-danger" value="Delete Selected Records" />
            }
            else
            {
             <p class="text-info, text-danger">No Records Found</p>
             <table class="table table-responsive table-bordered">
                 <thead>
                     <tr class="header_style">
                         <th scope="col">
                             Select
                         </th>
                         <th scope="col">
                             Employee ID
                         </th>
                         <th scope="col">
                             Name
                         </th>
                         <th scope="col">
                             Salary
                         </th>
                         <th scope="col">
                             City
                         </th>
                         <th scope="col">
                             Country
                         </th>
                     </tr>
                 </thead>
             </table>
            }
        }
    </div>
</div>

Right now the Edit and Delete buttons will not be working. We will discuss in later articles. Now run your application, you can see the records will be displayed in WebGrid. You can select record using checkbox and Click on "Delete Selected Records" to delete records.

Display and deleting record from webgrid
Share:

Saturday, 22 July 2017

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>
Share:

Saturday, 15 July 2017

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

Sunday, 9 July 2017

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>
Share:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

Ads By Chitika