Tuesday 17 December 2013

Practical use of Delegate

A Real Life Example of Delegates
Let's say there are three of you. You, your friend, and your brother. You're each in a different room in your house so you can't hear each other, even if you shout.
1)You are playing a computer game
2) Friend is building a puzzle
3) Brother is napping
Now, you three are going to stay in your room but you want to be informed if anything interesting is happening to the one of you. Let's say you (playing the computer game) want to know when your brother wakes up.
You could keep walking to the room, checking to see if he's napping, and then walking back to your room. But that would waste a lot of time / resources, and what if you miss when he's awake before he goes back to sleep? That would be bad.
Instead, you hand him a 2-way radio that works between your room and his room. And you inform him that when he wakes up, he should press a button on the radio and say "I'm awake". You are going to be listening to that radio, waiting for him to say he's awake. This, in essence, is how a delegate works.
You're creating an "object" (the radio) that allows you to listen in on an event you specify. You don't want him to send any other messages to you right now, except when he wakes up. And you want to know immediately when he does, so you can go over to his room and say hi. (the methods that are called when a delegate event fires). You're also currently specifying that only you are listening on his radio.
Let's say you want your friend to come into the room at the same time as you, and do something else entirely, like fluff your brother's pillow. You will then give him an identical radio, that also hooks into your brother's radio, and inform him to wait and listen for the "i'm awake" signal.
Then, when your brother wakes up, he says "I'm awake!" and both you and your friend walk into the room. You say hi, and your friend fluffs the pillow, then you both exit.
Later, if you decide you don't care to say hi anymore, you turn off your radio. Now, you have no idea when your brother is awake or not, because you aren't listening anymore.
So again, you are each classes in this example, and each of you have your own methods. You're playing a computer game (PlayComputerGame()), your friend is building a puzzle (BuildPuzzle()) and your brother is napping (Napping()).
You create a delegate (ImAwake) that you set your brother to do, when he wakes up. You listen in on that delegate (giving yourself a radio and turning it on), and when you receive the message, you fire a new method called SayHi()). Your friend is also wired up to the same delegate (using an identical radio) and fires the method FluffPillow().

Monday 2 December 2013

ASP.NET Web Services Versus WCF Services

1 File Format/Extension :
i) ASP.net service - '.asmx'
ii) WCF service - '.svc'
2 Hosting :
i) ASP.net service - Can be hosted in IIS also can be hosted in a Windows Service.
ii) WCF service - Very flexible, can be hosted in IIS, Windows Activation Services(WAS), Managed Windows Services and It also supports Self-Hosting.
3 Transport Protocols/Binding :
i) ASP.net service - It supports HTTP & TCP protocols along with custom binding.
ii) WCF service - supports HTTP, WS-HTTP, TCP, Custom, Named Pipes, MSMQ & P2P(Point to Point) etc.
4 Data Transformation :
i) ASP.net service - XML serializer for Data Transformation.
ii) WCF service - DataContractSerializer for Data Transformation.
5 Serialization NameSpace :
i) ASP.net service - System.XML.Serialization
ii) WCF service - System.RunTime.Serialization
6 Supported Operations :
i) ASP.net service - only One-Way and Request-Response type.
ii) WCF service - Includes One-Way, Request-Response and Duplex.
7 Encoding :
i) ASP.net service - It uses following encoding mechanisms -
XML1.0, MTOM (Message Transmission Optimization Mechanism), DIME (Direct Internet Message Encapsulation)
ii) WCF service - It uses following encoding mechanisms -
XML1.0, MTOM, Binary

Wednesday 23 October 2013

Failed to create Designer from any web Server Control

For this type of problem you should use same assembly version number in web.config file and add same version assembly in add reference  and use same version assembly in aspx page

<%@ Register assembly="Infragistics4.Web.v13.1, Version=13.1.20131.2157, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" namespace="Infragistics.Web.UI.GridControls" tagprefix="igtbl" %>

then version number  13.1.20131.2157 should be same at three places defined above
Web.config File
Add Reference
Aspx Page

Potential Dangerious Request

a potentially dangerous request.form value was detected from the client in asp.net 4.0

Solution :: In web.config file under System.Web write

<compilation debug="false" targetFramework="4.0" /> 
 <httpRuntime requestValidationMode="2.0"/>

Thursday 10 October 2013

Repeater control implementation by tarun developer

dataconnectivity u can give on page load event  means connectionstring

<asp:Repeater ID="Repeater1" runat="server">
            <HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>name</th>
<th>userID</th>
<th>password</th>
<th>dob</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td><%#DataBinder.Eval(Container.DataItem,"name")%></td>
<td><%#DataBinder.Eval(Container.DataItem,"userID")%></td>
<td><%#DataBinder.Eval(Container.DataItem,"password")%></td>
<td><%#DataBinder.Eval(Container.DataItem,"dob")%></td></tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>

        </asp:Repeater>

name ,userID,password,dob are table columns in database

Thursday 26 September 2013

Delete Duplicate Records from Table in SQL SERVER

DELETE FROM emp WHERE ID NOT IN (SELECT MIN(ID) FROM emp GROUP BY FName)

delete from tableName where UniqueColumn NOT IN (select MIN(UniqueColumn) from tableName GROUP BY DuplicateRecoedColumn/DeletedDuplicateColumn)

Monday 2 September 2013

Visual Studio Classification

 http://en.wikipedia.org/wiki/Microsoft_Visual_Studio

Editions feature grid

Editions feature grid[52]
Product Extensions Projects templates MSDN integration Debugging Profiling Static analysis IntelliTrace Unit test Code coverage Coded UI test Test impact analysis Load testing Lab management Architecture and modelling Windows Phone development
Express Yes Limited Essential Yes No No No No No No No No No No Yes
Professional Yes Yes Full or Essentials Yes No No No Yes No No No No No No Yes
Premium Yes Yes Full Yes Yes Yes No Yes Yes Yes Yes No No Read-only Yes
Ultimate Yes Yes Full Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
Test Professional No No Full No No No No No No No Yes No Yes No No

Version history

Prior to Visual Studio Version 4.0, there were Visual Basic 3, Visual C++, Visual FoxPro and Visual SourceSafe as separate products.
Product name Codename Internal
version
Supported .NET
Framework versions
Release date
Visual Studio N/A 4.0 N/A 1995-04
Visual Studio 97 Boston 5.0 N/A 1997-02
Visual Studio 6.0 Aspen 6.0 N/A 1998-06
Visual Studio .NET (2002) Rainier 7.0 1.0 2002-02-13
Visual Studio .NET 2003 Everett 7.1 1.1 2003-04-24
Visual Studio 2005 Whidbey 8.0 2.0, 3.0 2005-11-07
Visual Studio 2008 Orcas 9.0 2.0, 3.0, 3.5 2007-11-19
Visual Studio 2010 Dev10/Rosario 10.0 2.0, 3.0, 3.5, 4.0 2010-04-12
Visual Studio 2012 Dev11 11.0 2.0, 3.0, 3.5, 4.0, 4.5 2012-09-12
Visual Studio 2013 Dev12 12.0 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1 Upcoming

Monday 5 August 2013

upload a file in database and download from database

 string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
                Stream str = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(str);
                Byte[] size = br.ReadBytes((int)str.Length);
                using (con = new MySqlConnection(ss))
                {
                    con.Open();
                    using (cmd = new MySqlCommand("insert into referalprogram(Company_Id,File_Name,Referal_Description,File_Type,File_Data,Add_User_Id,Add_Date)values(@cid,@fname,@rd,@ftype,@fdata,@uid,@adddate)", con))
                    {
                        cmd.Parameters.Add(new MySqlParameter("@cid", Session["cid"]));
                        cmd.Parameters.Add(new MySqlParameter("@fname", filename));
                        cmd.Parameters.Add(new MySqlParameter("@rd", TextBox1.Text));
                        cmd.Parameters.Add(new MySqlParameter("@ftype", "application/word"));
                        cmd.Parameters.Add(new MySqlParameter("@fdata", size));
                        cmd.Parameters.Add(new MySqlParameter("@uid", Session["adduid"]));
                        cmd.Parameters.Add(new MySqlParameter("@adddate", curr));
                        cmd.ExecuteNonQuery();
                        con.Close();
                        TextBox1.Text = "";
                        Label4.Text = "Data has been Uploaded.";
                    }
                }


to download by clicking on a button in gridview

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Download")
            {
                int id=Convert.ToInt32(e.CommandArgument);
                //LinkButton lnkbtn = sender as LinkButton;
                //GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
                //int fileid = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
                //string name, type;
                using ( con = new MySqlConnection(ss))
                {
                    con.Open();
                    using (cmd = new MySqlCommand("select File_Name, File_Type, File_Data from referalprogram where Ref_Program_Id=@Id",con))
                    {
                        cmd.Parameters.Add(new MySqlParameter("@id", id));
                        dr = cmd.ExecuteReader();
                        if (dr.Read())
                        {
                            Response.ContentType = dr["File_Type"].ToString();
                            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["File_Name"] + "\"");
                            Response.BinaryWrite((byte[])dr["File_Data"]);
                            Response.End();
                        }
                    }
                }
            }
        }

highlight certain dates selected by dataReader from database

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
        AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Vehicle"
        DataValueField="Vehicle" Height="17px"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="144px">
        <asp:ListItem Selected="True">Select vehicle</asp:ListItem>
    </asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:rentcarConnectionString %>"
        SelectCommand="SELECT DISTINCT [Vehicle] FROM [booking]">
    </asp:SqlDataSource>
    <asp:Calendar ID="Calendar1" runat="server" BackColor="#FFFFCC"
        BorderColor="#FFCC66" BorderWidth="1px" DayNameFormat="Shortest"
        Font-Names="Verdana" Font-Size="8pt" ForeColor="#663399" Height="336px"
        ondayrender="Calendar1_DayRender" ShowGridLines="True" Width="902px">
        <DayHeaderStyle BackColor="#FFCC66" Font-Bold="True" Height="1px" />
        <NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
        <OtherMonthDayStyle ForeColor="#CC9966" />
        <SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
        <SelectorStyle BackColor="#FFCC66" />
        <TitleStyle BackColor="#990000" Font-Bold="True" Font-Size="9pt"
            ForeColor="#FFFFCC" />
        <TodayDayStyle BackColor="#FFCC66" ForeColor="White" />
    </asp:Calendar>
    <asp:DropDownList ID="DropDownList2" runat="server">
    </asp:DropDownList>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>


Coding


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

public partial class Default14 : System.Web.UI.Page
{
    public string ss;

    protected void Page_Load(object sender, EventArgs e)
    {
        ss = ConfigurationManager.ConnectionStrings["rentcarConnectionString"].ConnectionString;
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList2.Items.Clear();
        SqlConnection con = new SqlConnection(ss);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from booking where Vehicle='" + DropDownList1.SelectedValue.ToString() + "'", con);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            string sd = dr.GetValue(2).ToString();

            //Label1.Text = "sd;
            List<string> lists = new List<string>();
            lists.Add(sd);
            foreach (string s in lists)
            {
                DropDownList2.Items.Add(s);
                Calendar1.SelectedDates.Add(Convert.ToDateTime(s));
            }
        }
        dr.Close();
        con.Close();
    }
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
      
            if (e.Day.IsSelected)
            {
                e.Cell.Text = "booked";
            }
       
    }
}


to perform any action on selecting date then code

 protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        string sds =Calendar1.SelectedDate.ToShortDateString();
    
    }

Monday 29 July 2013

Framework and Platform

SOFTWARE FRAMEWORK
In computer programming, a software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user-written code, thus providing application-specific software. A software framework is a universal, reusable software platform to develop applications, products and solutions. Software frameworks include support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together all the different components to enable development of a project or solution.
Frameworks contain key distinguishing features that separate them from normal libraries:
  1. inversion of control – In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.[1]
  2. default behavior – A framework has a default behavior. This default behavior must be some useful behavior and not a series of no-ops.
  3. extensibility – A framework can be extended by the user usually by selective overriding or specialized by user code to provide specific functionality.
  4. non-modifiable framework code – The framework code, in general, is not allowed to be modified, excepting extensibility. Users can extend the framework, but not modify its code

Tuesday 23 July 2013

Row Command Event in Grid View



<asp:GridView ID="GridView1" runat="server"
                                        onrowcommand="GridView1_RowCommand" CellPadding="1" CellSpacing="2"
                                        GridLines="None" Width="850px">
                                        <Columns>
                                        <asp:TemplateField>
                                        <HeaderTemplate>Delete</HeaderTemplate>
                                        <ItemTemplate>
                                            <asp:Button ID="Button1" runat="server" Text="Delete" CommandName="DeleteRow"
                                                CommandArgument='<%#Eval("Message ID") %>' Height="24px" Width="81px" />
                                            <asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server" TargetControlID="Button1" ConfirmText="You want to delete this Message.">
                                            </asp:ConfirmButtonExtender>
                                            </ItemTemplate>
                                           
                                            </asp:TemplateField>
                                             
                                              <asp:TemplateField>
                                       <HeaderTemplate>Read</HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Button ID="Button2" runat="server" Text="Read" CommandName="Select"
                                                    CommandArgument='<%#Eval("Message ID") %>' Height="25px" Width="80px" />
                                            </ItemTemplate>
                                            </asp:TemplateField>
                                        </Columns>
                                        <HeaderStyle BackColor="Blue" ForeColor="White" Height="40px"
                                            HorizontalAlign="Center" />
                                        <RowStyle Height="30px" HorizontalAlign="Center" />
                                    </asp:GridView>

Command Argument contail same value as you are specifying in select command
if u rename any column by as keyword in select command then command argument will use renamed name  for ex original data column is Message_Id  you retrieve it as Message ID then command argument will use Message ID not Message_Id.


in code file

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
           
           
            if (e.CommandName == "DeleteRow")
            {
                int index =Convert.ToInt32(e.CommandArgument);
                //GridViewRow row = GridView1.Rows[index];
                //GridView1.DeleteRow(index);
                con = new MySqlConnection(ss);
                con.Open();
                cmd = new MySqlCommand("delete from message where Message_Id=@mid", con);
                cmd.Parameters.Add(new MySqlParameter("mid", index));
                cmd.ExecuteNonQuery();
                con.Close();
               
            }


        }

Validate a TextBox to contain only particular data

This code validate a text box to cantain only alphabets.
If u want to change then you can replace IsLetter to any type .


  protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        if (TextBox1.Text.All(chr => char.IsLetter(chr)))
        {
          
                Label1.Text = "ok";
           
        }
        else
        {
            Label1.Text = "not ok";
           
        }
    }

INDEX (Clustered and Non Clustered)

An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. An index contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to find the row or rows associated with the key values quickly and efficiently.
A table or view can contain the following types of indexes:
When multiple databases and multiple tables are joined, it's referred to as a cluster

  • Clustered
    • Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
    • The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
  • Nonclustered
    • Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
    • The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
    • You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, 900 bytes and 16 key columns, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns.

      Both clustered and nonclustered indexes can be unique. This means no two rows can have the same value for the index key. Otherwise, the index is not unique and multiple rows can share the same key value. For more information, see Create Unique Indexes.

      Indexes are automatically maintained for a table or view whenever the table data is modified.

Sunday 21 July 2013

Validation in ASP.NET using JAVA SCRIPT Or Restrict the Length of Control

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

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form1" runat="server">
    <div>
   
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="validate()" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <script type="text/javascript">
    function validate() {
        var textbox = document.getElementById('<% = TextBox1.ClientID %>').value;
        var drop = document.getElementById('<%=DropDownList1.ClientID %>').value;
        if (textbox == "") {
            alert("enter the value");
document.getElementById('<% = TextBox1.ClientID %>').focus();
            return false;
        }
        if (drop == "Select") {
            alert("selectany value ");
            return false;
        }
    }
</script>
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>Select</asp:ListItem>
            <asp:ListItem>yes</asp:ListItem>
            <asp:ListItem>no</asp:ListItem>
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Fore more visit http://www.codeproject.com/Tips/404274/Client-Side-Validation-using-JavaScript
If u want to restrict the length then use

  var drop = document.getElementById('<%=DropDownList1.ClientID %>').value.Length

then compare length to any number 

Saturday 20 July 2013

To select top nth record in sql server

select top 1 *  from ( select top 2 * from abc order by id desc  )sub order by id asc

it will select top 2nd from bottom

for seleting top 3rd from above

select top 1 *  from ( select top 3 * from abc order by id asc  )sub order by id desc



from Top

select top 1* from  (select Top 4 id from test1 order by id asc) sub order by id desc

from Bottom

select top 1* from  (select Top 4 id from test1 order by id desc) sub order by id asc

Monday 8 July 2013

Delete multiple Records in Gridview using CheckBoxes

<asp:GridView ID="gvAll" runat="server"
    AutoGenerateColumns = "false" Font-Names = "Arial"
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
    HeaderStyle-BackColor = "green" AllowPaging ="true"  
    OnPageIndexChanging = "OnPaging" DataKeyNames = "CustomerID"
    PageSize = "10" >
   <Columns>
    <asp:TemplateField>
        <HeaderTemplate>
            <asp:CheckBox ID="chkAll" runat="server"
              />
        </HeaderTemplate>
        <ItemTemplate>
            <asp:CheckBox ID="chk" runat="server"
             />
        </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "ContactName"
       HeaderText = "Contact Name"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "Country"
       HeaderText = "Country"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "City"
       HeaderText = "City"/>
   </Columns>
   <AlternatingRowStyle BackColor="#C2D69B"  />
</asp:GridView>
<asp:HiddenField ID="hfCount" runat="server" Value = "0" />
<asp:Button ID="btnDelete" runat="server" Text="Delete Checked Records"
   OnClientClick = "return ConfirmDelete();" OnClick="btnDelete_Click" />
You’ll notice above I have added a template field with checkboxes also I have added a check all checkbox in the Header Template of the ASP.net GridView Control. There’s a hidden field to store the count of the selected records and a delete button to trigger the delete operation. Paging is enabled for the GridView and there’s OnPageIndexChanging event that will be described later. CustomerID is assigned to the DataKeyNames property of the GridView which will allow us to uniquely identify each row
Data Binding the ASP.Net GridView control
I have used the Customers table from the Northwind Database for this example. The Customers table has some relationships with other tables hence it will not allow delete directly without removing the foreign key references. Hence to make it simple will create a new table called TestCustomers and use that instead. To create a clone table execute the following query.
SELECT * INTO TestCustomers
FROM Customers
The above query will create a new table TestCustomers and copy all the records from Customers table into TestCustomers. Thus now we can use it for out tutorial. The following function is used to databind the ASP.Net GridView control
C#
private void BindGrid()
{
    string constr = ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
    string query = "select * from TestCustomers";
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter(query, con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gvAll.DataSource = dt;
    gvAll.DataBind();
}
VB.Net
Private Sub BindGrid()
    Dim constr As String = ConfigurationManager _
                    .ConnectionStrings("conString").ConnectionString()
    Dim query As String = "select * from TestCustomers"
    Dim con As New SqlConnection(constr)
    Dim sda As New SqlDataAdapter(query, con)
    Dim dt As New DataTable()
    sda.Fill(dt)
    gvAll.DataSource = dt
    gvAll.DataBind()
End Sub
Maintaining the state of Checkboxes while paging
This is the core part of this example since its job is to keep track of the selected rows irrespective of which page it belongs and also maintain the state of the checkboxes while pagination so that user selections are not lost when he navigates from one page to another.
To facilitate this i have made use of the following two functions
1. GetData
The GetData function simply retrieves the records for which the user has checked the checkbox, adds them to an ArrayList and then saves the ArrayList to ViewState
C#
private void GetData()
{
    ArrayList arr;
    if (ViewState["SelectedRecords"] != null)
        arr = (ArrayList)ViewState["SelectedRecords"];
    else
        arr = new ArrayList();
    CheckBox chkAll = (CheckBox)gvAll.HeaderRow
                        .Cells[0].FindControl("chkAll");
    for (int i = 0; i < gvAll.Rows.Count; i++)
    {
        if (chkAll.Checked)
        {
            if (!arr.Contains(gvAll.DataKeys[i].Value))
            {
                arr.Add(gvAll.DataKeys[i].Value);
            }
        }
        else
        {
            CheckBox chk = (CheckBox)gvAll.Rows[i]
                               .Cells[0].FindControl("chk");
            if (chk.Checked)
            {
                if (!arr.Contains(gvAll.DataKeys[i].Value))
                {
                    arr.Add(gvAll.DataKeys[i].Value);
                }
            }
            else
            {
                if (arr.Contains(gvAll.DataKeys[i].Value))
                {
                    arr.Remove(gvAll.DataKeys[i].Value);
                }
            }
        }
    }
    ViewState["SelectedRecords"] = arr;
}
VB.Net
Private Sub GetData()
    Dim arr As ArrayList
    If ViewState("SelectedRecords") IsNot Nothing Then
         arr = DirectCast(ViewState("SelectedRecords"), ArrayList)
    Else
         arr = New ArrayList()
    End If
    Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
                    .Cells(0).FindControl("chkAll"), CheckBox)
    For i As Integer = 0 To gvAll.Rows.Count - 1
       If chkAll.Checked Then
             If Not arr.Contains(gvAll.DataKeys(i).Value) Then
                 arr.Add(gvAll.DataKeys(i).Value)
             End If
       Else
             Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
                                            .FindControl("chk"), CheckBox)
             If chk.Checked Then
                If Not arr.Contains(gvAll.DataKeys(i).Value) Then
                     arr.Add(gvAll.DataKeys(i).Value)
                End If
             Else
                If arr.Contains(gvAll.DataKeys(i).Value) Then
                     arr.Remove(gvAll.DataKeys(i).Value)
                End If
             End If
       End If
    Next
    ViewState("SelectedRecords") = arr
End Sub
GetData is called in the Page Load event of the ASP.Net web page in the following way
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
        GetData();
    BindGrid();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If IsPostBack Then
         GetData()
    End If
    BindGrid()
End Sub
2. SetData
The SetData function simply restores the saved state of the checkboxes from the ViewState
C#
private void SetData()
{
    int currentCount = 0;
    CheckBox chkAll = (CheckBox)gvAll.HeaderRow
                            .Cells[0].FindControl("chkAll");
    chkAll.Checked = true;
    ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
    for (int i = 0; i < gvAll.Rows.Count; i++)
    {
        CheckBox chk = (CheckBox)gvAll.Rows[i]
                        .Cells[0].FindControl("chk");
        if (chk != null)
        {
            chk.Checked = arr.Contains(gvAll.DataKeys[i].Value);
            if (!chk.Checked)
                chkAll.Checked = false;
            else
                currentCount++;
        }
    }
    hfCount.Value = (arr.Count - currentCount).ToString(); 
}
VB.Net
Private Sub SetData()
  Dim currentCount As Integer = 0
  Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
                        .Cells(0).FindControl("chkAll"), CheckBox)
  chkAll.Checked = True
  Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
                                        , ArrayList)
  For i As Integer = 0 To gvAll.Rows.Count - 1
     Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
                                         .FindControl("chk"), CheckBox)
     If chk IsNot Nothing Then
         chk.Checked = arr.Contains(gvAll.DataKeys(i).Value)
         If Not chk.Checked Then
                chkAll.Checked = False
         Else
                currentCount += 1
         End If
     End If
  Next
  hfCount.Value = (arr.Count - currentCount).ToString()
End Sub
The SetData method is called up in the OnPageIndexChanging event of the ASP.Net GridView in the following way
C#
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    gvAll.PageIndex = e.NewPageIndex;
    gvAll.DataBind();
    SetData();
}
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    gvAll.PageIndex = e.NewPageIndex
    gvAll.DataBind()
    SetData()
End Sub
Deleting multiple selected rows
Now when the delete button is clicked by the user the following event if triggered
C#
protected void btnDelete_Click(object sender, EventArgs e)
{
    int count = 0;
    SetData();
    gvAll.AllowPaging = false;
    gvAll.DataBind(); 
    ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
    count = arr.Count;
    for (int i = 0; i < gvAll.Rows.Count; i++)
    {
        if (arr.Contains(gvAll.DataKeys[i].Value))
        {
            DeleteRecord(gvAll.DataKeys[i].Value.ToString());
            arr.Remove(gvAll.DataKeys[i].Value);
        }
    }
    ViewState["SelectedRecords"] = arr;
    hfCount.Value = "0";
    gvAll.AllowPaging = true;
    BindGrid();
    ShowMessage(count);
}
VB.Net
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim count As Integer = 0
    SetData()
    gvAll.AllowPaging = False
    gvAll.DataBind()
    Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
                                    , ArrayList)
    count = arr.Count
    For i As Integer = 0 To gvAll.Rows.Count - 1
        If arr.Contains(gvAll.DataKeys(i).Value) Then
              DeleteRecord(gvAll.DataKeys(i).Value.ToString())
              arr.Remove(gvAll.DataKeys(i).Value)
        End If
    Next
    ViewState("SelectedRecords") = arr
    hfCount.Value = "0"
    gvAll.AllowPaging = True
    BindGrid()
    ShowMessage(count)
End Sub
In the above event handler I am simply looping through the GridView and checking if the record exists in the ArrayList, if the record exists then it is simply deleted using the DeleteRecord method. Finally I display the a JavaScript Alert Box to notify the user that the delete operation is finished using the ShowMessage method
DeleteRecord Method
The delete record method simply deletes the record from the database table based on CustomerID.
C#
private void DeleteRecord(string CustomerID)
{
    string constr = ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
    string query = "delete from TestCustomers " +
                    "where CustomerID=@CustomerID";
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@CustomerID", CustomerID);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}
VB.Net
Private Sub DeleteRecord(ByVal CustomerID As String)
    Dim constr As String = ConfigurationManager _
                        .ConnectionStrings("conString").ConnectionString
    Dim query As String = "delete from TestCustomers where" & _
                                " CustomerID=@CustomerID"
    Dim con As New SqlConnection(constr)
    Dim cmd As New SqlCommand(query, con)
    cmd.Parameters.AddWithValue("@CustomerID", CustomerID)
    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
End Sub
ShowMessage Method
 The ShowMessage method simply displays the amount of records deleted through a JavaScript Alert
C#
private void ShowMessage(int count)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type = 'text/javascript'>");
    sb.Append("alert('");
    sb.Append(count.ToString());
    sb.Append(" records deleted.');");
    sb.Append("</script>");
    ClientScript.RegisterStartupScript(this.GetType(),
                    "script", sb.ToString());
}
VB.Net
Private Sub ShowMessage(ByVal count As Integer)
     Dim sb As New StringBuilder()
     sb.Append("<script type = 'text/javascript'>")
     sb.Append("alert('")
     sb.Append(count.ToString())
     sb.Append(" records deleted.');")
     sb.Append("</script>")
     ClientScript.RegisterStartupScript(Me.GetType(), _
                        "script", sb.ToString())
End Sub
Client Side Scripting
I have made use of some JavaScript methods for the following methods
1.  Check-all checkbox functionality
2.  Confirmation before delete.
Check-all checkbox functionality
Check-all checkbox functionality has already explained by me in past. You can simply refer my article
Confirmation before delete
It would be a great feature to display a confirm box to the user stating that these many rows or records selected by you will be deleted. If the user presses OK delete operation will be performed else not. The following JavaScript function does it for us.
<script type = "text/javascript">
    function ConfirmDelete()
    {
       var count = document.getElementById("<%=hfCount.ClientID %>").value;
       var gv = document.getElementById("<%=gvAll.ClientID%>");
       var chk = gv.getElementsByTagName("input");
       for(var i=0;i<chk.length;i++)
       {
            if(chk[i].checked && chk[i].id.indexOf("chkAll") == -1)
            {
                count++;
            }
       }
       if(count == 0)
       {
            alert("No records to delete.");
            return false;
       }
       else
       {
            return confirm("Do you want to delete " + count + " records.");
       }
    }
</script>