Thursday 28 April 2011

Select All in Multiple Page GridView



Today I am blogging a cool concept - Select All and Multi selection feature with multiples Page in GridView. Sometimes, we may get a very challenging customer who required delivering what they have seen in popular websites like Google.

The implementation meets the following requirements (Divided into Functions):

Appearance:
  1. Required a GridView to show list records in multiple pages
  2. The normal row background color must be in a predefined color (CSS Class)
  3. The selected Row background color must be changed to predefined color (CSS class)

Row Selection
  1. Initially when the page gets loaded, the GridView must be selected with list of Ids assigned in code behind.
  2. There must be a Select column in the GridView to select each row. (So the user can select multiple row)
  3. Once a row is selected and move to another page, the selection made in old page must be retained. When the users comes back to the same page, the selected row must be shown as selected.

SelectAll
  1. There should be a Select All check box (in the header) at the Select column, which selects all the records in the current page.
  2. When the user selects Select All check box, it must select the entire row in the current page. Same goes to unselecting Select All.
  3. When page loaded the Select All checkbox must be selected If all the records in the current page has already been selected by Select All option or manually selecting all records. (so the user can unselect the page)
  4. Once all records get selected in the current page, there must be an Undo options which will undo all the selection on the current page and revert back the old status. It means the selection /unselecting before select all will be loaded back.
  5. The undo operation will be removed if any other operations like selecting any record in the current page or moving to another page.

Selecting All Page
  1. There must be an option to select all pages records in a single click. It must be provided with the GridiView itself and must be available in the entire page.
  2. Once the user selected Select all page records, there must be an option to undo the all page record selection. So if the user decided to Undo all page selection operation, the selection was made before all page records selection, must be revered back. It must be available in all pages.
  3. The Undo all page selection option must be available only till any further operation done on the GridView like (un)selecting any record on any page, (un)selecting all records in any page.
  4. Once the Undo operation removed by any further operation, there GridView selection mode must be changed to Unselect Mode. So there should be message with the GridView to let user to know All Page is selected already.

Unselect Mode
  1. Once the Select All Page operation done, the user can unselect any of the records / all records from any page.
  2. All the operation can be done in Row Selection, Select All is available here, but instead of selection it will be unselection.

Output
  1. All the selections must be retained internally in code/web controls. There must not be any database update (or any flat/xml file) until the user press Process/Submit button outside the GridView
  2. At any point, from the code behind there must be an option to know what are records selected and does all page selection done.

Before going to the actual implementation, I wish to let you know some points to remember.

  1. This implementation considers there will be CSS class for styling the normal and selected row style. So If you required to implement for Alternative row color (means three colors, 1 – Normal row 2 – Alternative Row, 3 – Selected Row, then you can change the same code using this post)
  2. As we are using CSS class for row styling, please make sure you are not having RowStyle, SelectedRowStyle, EditRowStyle, AlternatingRowStyle in your Grid.
  3. There are three hidden field control are used in this implementation.
    1. hndSelectedRowId – This hidden control is used to hold the selected row Ids. In this example Product Row Ids. It will be separated by comma (,). Incase if some rows required to be selected initially, pls make sure you assign the values in following way in code behind.
      hndSelectedRowId.Value = "2,16,20"; //C#Code
    2. hndSelectedRecordConfig - This hidden control is used to hold some information for internal operation. But initially, the count of all records should be assigned to this control from code behind.
      hndSelectedRecordConfig.Value = productViewList.Count.ToString(); // This must be assigned only one time when GridView is binding
    3. hndIsSelectAllInAllPage - This hidden control is used to hold, if all page records selection done. The value 0 (zero) tells – All page selection not done, 1 (one) – all page selection done. This control can be assigned 0 or 1 initially (if not 0 will assigned by default).
  4. As we are having Selection and Unselect Modes, the following way is used to get the list of selected Ids.
    1. When Select all page records option is not selected (means when hndIsSelectAllInAllPage = 0), the hndSelectedRowId control will contains only the selected records with , (comma) separator.
    2. When Select all page records option is selected (means when hndIsSelectAllInAllPage = 1), the hndSelectedRowId control will contains only the un selected records with , (comma) separator.
    3. So to know the records selected, you required to know hndIsSelectAllInAllPage value and hndSelectedRowId value.
    4. Important to know is, this implementation will not give selected Ids when Select all page records selected (when hndIsSelectAllInAllPage = 1). You can query the database to get the list of selected id (if Select all page records selected) using NOT IN with selected Ids from hndSelectedRowId. I had given a sample code in the example when pressing the Process button for the same.

I made this code to be up to some mark as I got limited time available. If someone feels the code could be done better, feel free to comment on the blog. I will work and update the post again.


I am using Northwind database for this example, so make sure to have Northwind database to use this sample. The comments on the code will explain more about the functionality of the code.

The implementation as follows:

In aspx script.
<asp:GridView ID="grdViewProducts" runat="server"
    AllowPaging="True" AutoGenerateColumns="False" TabIndex="1"
    DataKeyNames="ProductID" Width="100%"
    CellPadding="4" ForeColor="#333333" 
    onpageindexchanging="grdViewProducts_PageIndexChanging">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
        <asp:BoundField DataField="CompanyName" HeaderText="Supplier" />
        <asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
        <asp:BoundField DataField="CategoryName" HeaderText="Category" />
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit"/>
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" DataFormatString="{0:#0.00}" />
        <asp:TemplateField HeaderText="Select">
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkSelectAll" onclick="SelectAll(this.id)" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkSelect" onclick="SelectRow(this.id)" />
                <asp:Label runat="server" ID="lblProductId" Text='<%# Eval("ProductID") %>' CssClass="InvisibleControl"></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:CheckBox runat="server" ID="chkSelectAll1" onclick="SelectAll()" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Right" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="100px" OnClick="btnProcess_Click" />
<asp:Label runat="server" ID="lblMessage" ></asp:Label>
<asp:HiddenField runat="server" ID="hndSelectedRecordConfig" Value="0" />
<asp:HiddenField runat="server" ID="hndIsSelectAllInAllPage" Value="0" />
<asp:HiddenField ID="hndSelectedRowId" runat="server" Value="" />
JavaScript
var Const_LastCol_Index = 6;
var IsFooterExist = 1; //(0 - No, 1 - Yes)
var SelectedRowIds = '';
var IsUndoSelectAllPage = 1;

// I am calling a Javascript function to change the selected row color on page load
var browserName = navigator.appName;
if (browserName == "Microsoft Internet Explorer") {
    window.onload = SelectGridOnLoad;
}
else {
    if (browserName == "Netscape") //google chrome app.Name
    {
        setTimeout("SelectGridOnLoad()", 500);
    }
    else {
        window.onload = SelectGridOnLoad; // helps with Opera
    }
}

function SelectGridOnLoad() {
    var varDataRowStartIndex = 1;
    var NoofRowSelected = 0;

    if (document.getElementById("MessageInfoRow") != null) varDataRowStartIndex = 2;
    
    // Looping all the row (Here - 1 is used as I have footer in the Grid View and starting from 1 Row (0 is Header)
    // So if you dont have Footer required to loop till end of the row (ie., no -1).
    for (var intRow = varDataRowStartIndex; intRow < document.getElementById('<%= grdViewProducts.ClientID %>').rows.length - IsFooterExist; intRow++) {

        // Declaring variable for Holding Values
        var vCheckById = 0;
        var vProductId = '';
        
        // Getting the GridView Row
        var gridRow = document.getElementById('<%= grdViewProducts.ClientID %>').rows[intRow];
        
        for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the Row cell
        {
            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {

                // Getting Check box Id (to know the check box selected)
                if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("chkSelect") != -1)
                    vCheckById = gridRow.cells[Const_LastCol_Index].childNodes[intCell].id;

                // Getting the label value
                if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("lblProductId") != -1) {
                    if (browserName == "Microsoft Internet Explorer")  //Getting the ProductId
                        vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].innerText;
                    else
                        vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].textContent;
                }
            }
        }

        if (document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "1") { // If Select All page already selected
        
            var vSelecteIds = "," + document.getElementById('<%= hndSelectedRowId.ClientID %>').value + ",";
            if (vSelecteIds.indexOf("," + vProductId + ",") != -1) { // Means Selected
                document.getElementById(vCheckById).checked = false;
                gridRow.className = "NormalRowStyle";
            }
            else { // For normal row
                document.getElementById(vCheckById).checked = true;
                gridRow.className = "SelectedRowStyle";
                NoofRowSelected = parseInt(NoofRowSelected) + 1;
            }
        }
        else {
        
            var vSelecteIds = "," + document.getElementById('<%= hndSelectedRowId.ClientID %>').value + ",";
            if (vSelecteIds.indexOf("," + vProductId + ",") != -1) { // Means Selected
                document.getElementById(vCheckById).checked = true;
                gridRow.className = "SelectedRowStyle";
                NoofRowSelected = parseInt(NoofRowSelected) + 1;
            }
            else { // For normal row
                document.getElementById(vCheckById).checked = false;
                gridRow.className = "NormalRowStyle";
            }
        }
    }

    var gridRow = document.getElementById('<%= grdViewProducts.ClientID %>').rows[0];
    for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the Row cell
    {
        if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {
            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("chkSelectAll") != -1)
            {
                if (NoofRowSelected == document.getElementById('<%= grdViewProducts.ClientID %>').rows.length - varDataRowStartIndex - IsFooterExist)
                    document.getElementById(gridRow.cells[Const_LastCol_Index].childNodes[intCell].id).checked = true;
                 else
                    document.getElementById(gridRow.cells[Const_LastCol_Index].childNodes[intCell].id).checked = false;
            }
        }
    }
    
    ShowMessage(0);
}
function SelectRow(Id) {

    var vProductId = 0;

    var gridRow = document.getElementById(Id).parentNode.parentNode;

    // Getting the Product Id
    for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the last Row controls
    {
        if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {

            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("lblProductId") != -1) {
                if (browserName == "Microsoft Internet Explorer")  //Getting the ProductId
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].innerText;
                else
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].textContent;
            }
        }
    }
    if (document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "1") 
    {
        if (parseInt(IsUndoSelectAllPage) == 1) {
            IsUndoSelectAllPage = 0;
            document.getElementById('<%= hndSelectedRowId.ClientID %>').value = '';
        }
        if (document.getElementById(Id).checked == true) // If Selected
        {
            RemoveSelectedId(vProductId, 1);
            gridRow.className = "SelectedRowStyle";
        }
        else // If unselected - Replace the style to normal row
        {
            AddSelectedId(vProductId, 1);
            document.getElementById(Id).parentNode.parentNode.className = "NormalRowStyle";
        }
        ShowMessage(2);
    }
    else {
        if (document.getElementById(Id).checked == true) // If Selected
        {
            AddSelectedId(vProductId, 1);
            gridRow.className = "SelectedRowStyle";
        }
        else // If unselected - Replace the style to normal row
        {
            RemoveSelectedId(vProductId, 1);
            document.getElementById(Id).parentNode.parentNode.className = "NormalRowStyle";
        }
        ShowMessage(0);
    }
}
function SelectAll(Id) {

    var varDataRowStartIndex = 1;
    if (document.getElementById("MessageInfoRow") != null) varDataRowStartIndex = 2;
    
    var varNoofRow = document.getElementById('<%= grdViewProducts.ClientID %>').rows.length;
    
    for (var intRow = varDataRowStartIndex; intRow < varNoofRow - IsFooterExist; intRow++) {
        // Declaring variable for Holding Values
        var vCheckById = '';
        var vProductId = '';
        
        // Getting the GridView Row
        var gridRow = document.getElementById('<%= grdViewProducts.ClientID %>').rows[intRow];

        for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the Row cell
        {
            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {

                // Getting Check box Id (to know the check box selected)
                if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("chkSelect") != -1)
                    vCheckById = gridRow.cells[Const_LastCol_Index].childNodes[intCell].id;
                    
                // Getting the label value
                if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("lblProductId") != -1)
                    if (browserName == "Microsoft Internet Explorer")  //Getting the ProductId
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].innerText;
                else
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].textContent;

            }
        }

        if (document.getElementById(Id).checked == true) {// If All Selected
            
            if (document.getElementById(vCheckById).checked == false) {
                document.getElementById(vCheckById).checked = true;
                gridRow.className = "SelectedRowStyle";

                if (document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "0")
                    AddSelectedId(vProductId, 1);
                else
                    RemoveSelectedId(vProductId, 1);
                    
                SelectedRowIds = SelectedRowIds + "{" + vProductId + ",0}"; // For undo operation
            }
            else
                SelectedRowIds = SelectedRowIds + "{" + vProductId + ",1}"; // For undo operation
        }

        if (document.getElementById(Id).checked == false) {// If All not Selected
            if (document.getElementById(vCheckById).checked == true) { // and the row already selected
            
                document.getElementById(vCheckById).checked = false;
                gridRow.className = "NormalRowStyle";

                if (document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "0")
                    RemoveSelectedId(vProductId, 1);
                else
                    AddSelectedId(vProductId, 1);
                SelectedRowIds = SelectedRowIds + "{" + vProductId + ",1}"; // For undo operation
            }
            else
                SelectedRowIds = SelectedRowIds + "{" + vProductId + ",0}"; // For undo operation
        }
    }
    if ((document.getElementById('ctl00_ContentPlaceHolder1_hndIsSelectAllInAllPage').value == "1") && (parseInt(IsUndoSelectAllPage) == 1)) {
        IsUndoSelectAllPage = 0
    }
    SelectedIds = document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",{")[1];
    if (SelectedIds.length > 0) SelectedIds = SelectedIds.substring(0, SelectedIds.length - 1)

    document.getElementById('ctl00_ContentPlaceHolder1_hndSelectedRecordConfig').value =
            document.getElementById('ctl00_ContentPlaceHolder1_hndSelectedRecordConfig').value.split(",")[0] + "," +
            document.getElementById('ctl00_ContentPlaceHolder1_hndSelectedRecordConfig').value.split(",")[1] + "," +
            IsUndoSelectAllPage + ",{" + SelectedIds + "}";

    ShowMessage(1);
}

function ShowMessage(callType) {

    var NoofRowSelected = 0;
    var TotalRowCount = 0;
    var SelectedIds = '';
    
    if (document.getElementById('<%= hndSelectedRowId.ClientID %>').value.length > 0)
        NoofRowSelected = document.getElementById('<%= hndSelectedRowId.ClientID %>').value.split(",").length;

    if (document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.indexOf(",") > -1) {
        TotalRowCount = document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",")[0];
        IsUndoSelectAllPage = document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",")[2];
        SelectedIds = document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",{")[1];
        if (SelectedIds.length > 0) SelectedIds = SelectedIds.substring(0, SelectedIds.length - 1)
    }
    else {
        SelectedIds = document.getElementById('<%= hndSelectedRowId.ClientID %>').value;
        if (parseInt(document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value) > 0)
            TotalRowCount = document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value;
        else
            TotalRowCount = "0";
    }
    document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value =
        document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",")[0] + "," + 
        NoofRowSelected + "," + IsUndoSelectAllPage + ",{" + SelectedIds + "}";
    
    var divMessage;
    
    if (document.getElementById("MessageInfoRow") == null) {

        // Getting the table
        var tableProducts = document.getElementById('<%= grdViewProducts.ClientID %>');
        var NoofCells = document.getElementById('<%= grdViewProducts.ClientID %>').rows[1].cells.length; // First Row cell count for spanning the cells

        var newRow = tableProducts.insertRow(1); // Inserting a Row after header
        newRow.setAttribute("id", "MessageInfoRow");
        var newCell = newRow.insertCell(0) // Inserting a cell
        newCell.className = "InsertedRowStyle";
        
        divMessage = document.createElement('div');
        divMessage.setAttribute("id", "MessageInfo");
        newCell.appendChild(divMessage);
        newCell.colSpan = NoofCells;
        varDataRowStartIndex = 2;
    }
    else
        divMessage = document.getElementById("MessageInfo");

    var varMessage = '';

    if ((document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "1") && (parseInt(IsUndoSelectAllPage) == 1)) {
        if (parseInt(TotalRowCount) > 0)
            varMessage = "All " + TotalRowCount;
        else
            varMessage = "All ";
    }
    else {
        if (parseInt(TotalRowCount) > 0)
            varMessage = NoofRowSelected + " (out of " + TotalRowCount + ")";
        else
            varMessage = NoofRowSelected;
    }

    if (parseInt(document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value) == 0) {
        if (parseInt(callType) == 0)
            divMessage.innerHTML = varMessage + " records has been selected. <a href='#' onclick=SelectAllPage()>Select all page records</a>";
        else
            //if (SelectedRowIds.length > 0)
            divMessage.innerHTML = varMessage + " records has been selected. <a href='#' onclick=UndoSelectAll()>Un do</a> <a href='#' onclick=SelectAllPage()>Select all page records</a>";
    }
    else {
        if (parseInt(IsUndoSelectAllPage) == 1)
            divMessage.innerHTML = varMessage + " records has been selected. <a href='#' onclick=UndoSelectionAllPage()>Undo all page selection</a>";
        else
            if (SelectedRowIds.length > 0)
                divMessage.innerHTML = varMessage + " records has been unselected. (<b>All Page is selected already</b>) <a href='#' onclick=UndoSelectAll()>Un do</a>";
            else
                divMessage.innerHTML = varMessage + " records has been unselected. (<b>All Page is selected already</b>)";
    }
}
function SelectRow(Id) {

    var vProductId = 0;

    var gridRow = document.getElementById(Id).parentNode.parentNode;

    // Getting the Product Id
    for (var intCell = 0; intCell < gridRow.cells[Const_LastCol_Index].childNodes.length; intCell++) // Looping the last Row controls
    {
        if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id != null) {

            if (gridRow.cells[Const_LastCol_Index].childNodes[intCell].id.indexOf("lblProductId") != -1) {
                if (browserName == "Microsoft Internet Explorer")  //Getting the ProductId
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].innerText;
                else
                    vProductId = gridRow.cells[Const_LastCol_Index].childNodes[intCell].textContent;
            }
        }
    }
    if (document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "1") 
    {
        if (parseInt(IsUndoSelectAllPage) == 1)
        {
            IsUndoSelectAllPage = 0;
            document.getElementById('<%= hndSelectedRowId.ClientID %>').value = '';
        }
        if (document.getElementById(Id).checked == true) // If Selected
        {
            RemoveSelectedId(vProductId, 1);
            gridRow.className = "SelectedRowStyle";
        }
        else // If unselected - Replace the style to normal row
        {
            AddSelectedId(vProductId, 1);
            document.getElementById(Id).parentNode.parentNode.className = "NormalRowStyle";
        }
        ShowMessage(0);
    }
    else 
    {
        if (document.getElementById(Id).checked == true) // If Selected
        {
            AddSelectedId(vProductId, 1);
            gridRow.className = "SelectedRowStyle";
        }
        else // If unselected - Replace the style to normal row
        {
            RemoveSelectedId(vProductId, 1);
            document.getElementById(Id).parentNode.parentNode.className = "NormalRowStyle";
        }
        ShowMessage(0);
    }
}
function SelectAllPage() {
    document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value = "1";

    document.getElementById('<%= hndSelectedRowId.ClientID %>').value = '';

    IsUndoSelectAllPage = 1;
    SelectGridOnLoad();
}
function UndoSelectionAllPage() {
    document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value = "0";

    var vSelectedIds = document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",{");

    document.getElementById('<%= hndSelectedRowId.ClientID %>').value = vSelectedIds[1].substring(0, vSelectedIds[1].length - 1);
    SelectGridOnLoad();
}
function UndoSelectAll() {
    SelectedId = SelectedRowIds.substring(1, SelectedRowIds.length - 1).split("}{");
    var vSelectedId = "," + document.getElementById('<%= hndSelectedRowId.ClientID %>').value + ",";

    for (var varIndex = 0; varIndex < SelectedId.length; varIndex++) {
        if (document.getElementById('<%= hndIsSelectAllInAllPage.ClientID %>').value == "0") {
            if (parseInt(SelectedId[varIndex].split(",")[1]) == 0)
                RemoveSelectedId(SelectedId[varIndex].split(",")[0]);
            else
                AddSelectedId(SelectedId[varIndex].split(",")[0]);
        }
        else {
            if (parseInt(SelectedId[varIndex].split(",")[1]) == 0)
                AddSelectedId(SelectedId[varIndex].split(",")[0]);
            else
                RemoveSelectedId(SelectedId[varIndex].split(",")[0]);
        }
    }
    SelectedRowIds = '';
    SelectGridOnLoad();
}
function RemoveSelectedId(vProductId, vUpdateConfig) {
    var vSelectedId = "," + document.getElementById('<%= hndSelectedRowId.ClientID %>').value + ",";
    vSelectedId = vSelectedId.replace("," + vProductId + ",", ","); // Removing the Id

    vSelectedId = vSelectedId.replace(/,,/g, ","); // Replacing all ,, ,,, ,,,, etc., to ,
    vSelectedId = vSelectedId.substr(1, vSelectedId.length - 2); // Removing , both the end and assigning
    document.getElementById('<%= hndSelectedRowId.ClientID %>').value = vSelectedId;

    document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value =
            document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",")[0] + "," +
            (vSelectedId.length == 0?0:vSelectedId.split(",").length) + "," + IsUndoSelectAllPage + ",{" + vSelectedId + "}";
}
function AddSelectedId(vProductId, vUpdateConfig) {
    var vSelectedId = "," + document.getElementById('<%= hndSelectedRowId.ClientID %>').value + ",";
    if (vSelectedId.indexOf("," + vProductId + ",") == -1) {
        var vSelectedId = document.getElementById('<%= hndSelectedRowId.ClientID %>').value;
        vSelectedId += "," + vProductId;

        vSelectedId = vSelectedId.replace(/,,/g, ","); // Replacing all ,, ,,, ,,,, etc., to ,
        while (vSelectedId.substring(0, 1) == ",") vSelectedId = vSelectedId.substring(1);

        document.getElementById('<%= hndSelectedRowId.ClientID %>').value = vSelectedId;
        document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value =
            document.getElementById('<%= hndSelectedRecordConfig.ClientID %>').value.split(",")[0] + "," +
            vSelectedId.split(",").length + "," + IsUndoSelectAllPage + ",{" + vSelectedId + "}";
    }
}
C# Codebehind
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindGrid();
        hndIsSelectAllInAllPage.Value = "0";
        hndSelectedRowId.Value = "2,16,20";
    }
}

/// <summary>
/// Method which binds the data to the Grid
/// </summary>
private void BindGrid()
{
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString))
    {

        SqlCommand command = new SqlCommand(
               "SELECT ProductID, ProductName, CompanyName, CategoryName, " +
               "QuantityPerUnit, UnitPrice FROM Products " +
               "JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " +
               "JOIN Categories ON Products.CategoryID = Categories.CategoryID ", connection);

        connection.Open();
        SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);

        IList<ProductView> productViewList = new List<ProductView>();
        while (dr.Read())
        {
            ProductView productView = new ProductView();
            productView.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
            productView.ProductName = dr["ProductName"].ToString();
            productView.CompanyName = dr["CompanyName"].ToString();
            productView.CategoryName = dr["CategoryName"].ToString();
            productView.QuantityPerUnit = dr["QuantityPerUnit"].ToString();
            productView.UnitPrice = Convert.ToDouble(dr["UnitPrice"].ToString());
            productViewList.Add(productView);
        }
        grdViewProducts.DataSource = productViewList;
        grdViewProducts.DataBind();
        if (!Page.IsPostBack) // Must be assigned only at the first time.
            hndSelectedRecordConfig.Value = productViewList.Count.ToString();
    }
}

protected void btnProcess_Click(object sender, EventArgs e)
{
    if (grdViewProducts.Rows.Count > 0)
    {
        string strMessage = "<br />Selected Row Id : " + hndSelectedRowId.Value +
                            "<br />Is All Page selected : " + (hndIsSelectAllInAllPage.Value == "1" ? "Yes" : "No") +
                            "<br />The Selected Products Query : <b>Select * From Products Where ProductID " + (hndIsSelectAllInAllPage.Value == "1" ? "NOT IN" : "IN") + "(" + hndSelectedRowId.Value + ")";
        lblMessage.Text = strMessage;
    }
}

protected void grdViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grdViewProducts.PageIndex = e.NewPageIndex;
    BindGrid();
}
VB Codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindGrid()
            hndIsSelectAllInAllPage.Value = "0"
            hndSelectedRowId.Value = "2,16,20"
        End If
    End Sub
    Private Sub BindGrid()
        Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SQLConnection").ConnectionString)

            Dim command As New SqlCommand("SELECT ProductID, ProductName, CompanyName, CategoryName, " & "QuantityPerUnit, UnitPrice FROM Products " & "JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " & "JOIN Categories ON Products.CategoryID = Categories.CategoryID ", connection)

            connection.Open()
            Dim dr As SqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection)

            Dim productViewList As IList(Of ProductView) = New List(Of ProductView)()
            While dr.Read()
                Dim productView As New ProductView()
                productView.ProductID = Convert.ToInt32(dr("ProductID").ToString())
                productView.ProductName = dr("ProductName").ToString()
                productView.CompanyName = dr("CompanyName").ToString()
                productView.CategoryName = dr("CategoryName").ToString()
                productView.QuantityPerUnit = dr("QuantityPerUnit").ToString()
                productView.UnitPrice = Convert.ToDouble(dr("UnitPrice").ToString())
                productViewList.Add(productView)
            End While
            grdViewProducts.DataSource = productViewList
            grdViewProducts.DataBind()
            If Not Page.IsPostBack Then ' Must be assigned only at the first time.
                hndSelectedRecordConfig.Value = productViewList.Count.ToString()
            End If
        End Using
    End Sub
    Protected Sub btnProcess_Click(ByVal sender As Object, ByVal e As EventArgs)
        If grdViewProducts.Rows.Count > 0 Then
            Dim strMessage As String = ("<br />Selected Row Id : " + hndSelectedRowId.Value & "<br />Is All Page selected : " & (If(hndIsSelectAllInAllPage.Value = "1", "Yes", "No")) & "<br />The Selected Products Query : <b>Select * From Products Where ProductID " & (If(hndIsSelectAllInAllPage.Value = "1", "NOT IN", "IN")) & "(") + hndSelectedRowId.Value & ")"
            lblMessage.Text = strMessage
        End If
    End Sub
    Protected Sub grdViewProducts_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        grdViewProducts.PageIndex = e.NewPageIndex
        BindGrid()
    End Sub
body
{
 
}

.NormalRowStyle
{
 background-color:#F7F6F3;
 color:#333333;
}

.SelectedRowStyle
{
 background-color:#F7BE81;
 color:#333333;
}

.InvisibleControl
{
 display:none;
}

.InsertedRowStyle
{
 background-color:#D0F5A9;
 height:20px;
}
public class ProductView
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string CompanyName { get; set; }
    public string CategoryName { get; set; }
    public string QuantityPerUnit { get; set; }
    public double UnitPrice { get; set; }
}
Public Class ProductView
    Public Property ProductID() As Integer
        Get
            Return m_ProductID
        End Get
        Set(ByVal value As Integer)
            m_ProductID = value
        End Set
    End Property
    Private m_ProductID As Integer
    Public Property ProductName() As String
        Get
            Return m_ProductName
        End Get
        Set(ByVal value As String)
            m_ProductName = value
        End Set
    End Property
    Private m_ProductName As String
    Public Property CompanyName() As String
        Get
            Return m_CompanyName
        End Get
        Set(ByVal value As String)
            m_CompanyName = value
        End Set
    End Property
    Private m_CompanyName As String
    Public Property CategoryName() As String
        Get
            Return m_CategoryName
        End Get
        Set(ByVal value As String)
            m_CategoryName = value
        End Set
    End Property
    Private m_CategoryName As String
    Public Property QuantityPerUnit() As String
        Get
            Return m_QuantityPerUnit
        End Get
        Set(ByVal value As String)
            m_QuantityPerUnit = value
        End Set
    End Property
    Private m_QuantityPerUnit As String
    Public Property UnitPrice() As Double
        Get
            Return m_UnitPrice
        End Get
        Set(ByVal value As Double)
            m_UnitPrice = value
        End Set
    End Property
    Private m_UnitPrice As Double
End Class

This code has been tested with IE 6.0/8.0, Chrome 10.0, Firefox 3.6, Opera 11.01

Here is the output of the example.



download the source code in C# here and in VB here

6 Responses to “Select All in Multiple Page GridView”

  • Anonymous says:
    22 June 2011 at 17:51

    Excellent!!..You are the Programmer

  • Thirumalai M says:
    22 June 2011 at 22:08

    Thank you dude!!

  • Anonymous says:
    2 February 2012 at 16:30

    Excellent Work

  • Anonymous says:
    14 April 2012 at 16:05

    I must say your article worked for me as LIGHT HOUSE. Now my ship(project:-) is going in right direction...Thanks Man

  • Thirumalai M says:
    17 April 2012 at 13:08

    Thanks man.. happy to see your comment.

  • Anonymous says:
    3 September 2012 at 17:13

    grt friends.. thanks

Post a Comment