locked
Paging custom page size RRS feed

Answers

  • User-1509636757 posted

    Since you are implementing Custom Paging with PagerTemplate; I think you will require to implement these pages numbers as well. I would be using Repeater control inside PagerTemplate and decide the numbers to be displayed (for example if total number of records are 55 and currently page size if 5 then I would do if (55/5) < 10 then use that number as max number else use 10 as max number; and bind a repeater with 1 to 10 (or the max number) numbers wrapped each number with a link button (again you will be using CommandName as "Page" and the particular page number as CommandArgument of the LinkButtons).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 5, 2017 5:29 PM

All replies

  • User3690988 posted

    If your code resembles the c-sharpcorner code, the second parameter passed into the GetPageData routine is the page count.  In this case 10:

     GetPageData(0, 10);

    Try passing the value of the per page DDL as the page count parameter when calling GetPageData:

    GetPageData(e.NewPageIndex, ddlPerPage.SelectedValue);



    Thursday, June 1, 2017 2:03 PM
  • User-1509636757 posted

    Now I want to specify the page size dynamically, something similar to this.

    Create a DropDownList with the allowable PageSize (5, 10, 15, 25, 50) in your application and pass the SelectedValue in GetPageData(0, 10); instead of hard-coded 10 value as:

    GetPageData(e.NewPageIndex, ddlPageSize.SelectedValue);

    Also under SelectedIndexChanged event of ddlPageSize (I mean the DropDownList that you would be creating to change the Page Size), you will require to set the PageSize of GridView and rebind the Grid as:

    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView1.PageSize = ddlPageSize.SelectedValue;
    GetPageData(e.NewPageIndex, ddlPageSize.SelectedValue);
    }

     

    Thursday, June 1, 2017 5:59 PM
  • User-614943948 posted

    Thanks for response bro. How can I place that DropDown right at the bottom of the gridview next to the page numbers?

    Another Issue .....

    protected void pageSize_SelectedIndexChanged(object sender, EventArgs e)
            {
                grdReport.PageSize = Convert.ToInt16(pageSize.SelectedValue);
                GetLoginHistoryDetails(1, Convert.ToInt16(pageSize.SelectedValue));
            }
    <asp:DropDownList ID="pageSize" runat="server" OnSelectedIndexChanged="pageSize_SelectedIndexChanged">
                        <asp:ListItem>5</asp:ListItem>
                        <asp:ListItem>10</asp:ListItem>
                        <asp:ListItem>15</asp:ListItem>
                        <asp:ListItem>20</asp:ListItem>
                    </asp:DropDownList>

    Page size index change isn't getting invoked while changing the value

    Friday, June 2, 2017 5:56 AM
  • User-1509636757 posted

    How can I place that DropDown right at the bottom of the gridview next to the page numbers?

    You are implementing Custom Paging, are you using DataPager? Can you post your design code?

    Friday, June 2, 2017 6:03 AM
  • User-614943948 posted

    I temporarily removed DataPage, I will post the design code shortly.

    Friday, June 2, 2017 6:15 AM
  • User-614943948 posted

    This is the complete source code.. Pleas ignore my previous message. It worked after setting AutoPostBack to true

    <div class="row-fluid" style="height: 70%; background-color: White; overflow: auto">
                    <asp:GridView ID="grdReport" runat="server" EmptyDataText="No Login history record found."
                        AllowPaging="True" AllowCustomPaging="true"
                        AutoGenerateColumns="False" PageSize="10" CssClass="Table Table-striped Table-bordered Table-hover"
                        EnableTheming="False" OnPageIndexChanging="grdReport_PageIndexChanging">
                        <Columns>
                            <asp:BoundField DataField="userid" HeaderText="User ID" />
                            <asp:BoundField DataField="LoginDate" HeaderText="Date" />
                            <asp:BoundField DataField="LoginTime" HeaderText="Time" />
                            <asp:BoundField DataField="Success" HeaderText="Success" />
                            <asp:BoundField DataField="Reason" HeaderText="Reason" />
                        </Columns>
                        <HeaderStyle Font-Size="12px" />
                        <PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" LastPageText="Last" 
                            NextPageText="Next" PreviousPageText="Previous"/>
                    </asp:GridView>
                </div>
                <div>
                    <asp:DropDownList ID="pageSize" runat="server" OnSelectedIndexChanged="pageSize_SelectedIndexChanged">
                        <asp:ListItem>5</asp:ListItem>
                        <asp:ListItem>10</asp:ListItem>
                        <asp:ListItem>15</asp:ListItem>
                        <asp:ListItem>20</asp:ListItem>
                    </asp:DropDownList>
                </div>

    Friday, June 2, 2017 6:18 AM
  • User-1509636757 posted

    You can add this DropDownList by using PagerTemplate. With the help of PagerTemplate, it will be easy to add custom controls and give them CommandName and CommandArgument to execute appropriate pager functionalities. You can take a look at this MSDN article with example, that represents how you can use these Pager commands along with custom controls in PagerTemplate: GridView.PagerTemplate Property (System.Web.UI.WebControls)

    Typically, button controls are added to the pager template to perform the paging operations. The GridView control performs a paging operation when a button control with its CommandName property set to "Page" is clicked. The button's CommandArgument property determines the type of paging operation to perform. The following table lists the command argument values supported by the GridView control.

    CommandArgument value

    Description

    "Next"

    Navigates to the next page.

    "Prev"

    Navigates to the previous page.

    "First"

    Navigates to the first page.

    "Last"

    Navigates to the last page.

    Integer value

    Navigates to the specified page number.

    Here is an example:

    <asp:GridView ID="grdReport" runat="server" EmptyDataText="No Login history record found."
        AllowPaging="True" AllowCustomPaging="true"
        AutoGenerateColumns="False" PageSize="10" CssClass="Table Table-striped Table-bordered Table-hover"
        EnableTheming="False" OnPageIndexChanging="grdReport_PageIndexChanging" OnRowDataBound="grdReport_RowDataBound">
        <Columns>
            <asp:BoundField DataField="userid" HeaderText="User ID" />
            <asp:BoundField DataField="LoginDate" HeaderText="Date" />
            <asp:BoundField DataField="LoginTime" HeaderText="Time" />
            <asp:BoundField DataField="Success" HeaderText="Success" />
            <asp:BoundField DataField="Reason" HeaderText="Reason" />
        </Columns>
        <HeaderStyle Font-Size="12px" />
        <PagerTemplate>
            <table width="100%">
                <tr>
                    <td style="width: 70%">
                        <asp:Label ID="MessageLabel"
                            ForeColor="Blue"
                            Text="Select Page Size:"
                            runat="server" />
                        <asp:DropDownList ID="PageDropDownList"
                            AutoPostBack="true"
                            OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged"
                            runat="server">
                            <asp:ListItem>5</asp:ListItem>
                            <asp:ListItem>10</asp:ListItem>
                            <asp:ListItem>15</asp:ListItem>
                            <asp:ListItem>20</asp:ListItem>
                        </asp:DropDownList>
                    </td>
                    <td style="width: 70%; text-align: right">
                        <asp:ImageButton ImageUrl="~/images/first.png" CommandArgument="First" CommandName="Page" runat="server" />
                        <asp:ImageButton ImageUrl="~/images/prev.png" CommandArgument="Prev" CommandName="Page" runat="server" />
                        <asp:Label ID="CurrentPageLabel"
                            ForeColor="Blue"
                            runat="server" />
                        <asp:ImageButton ImageUrl="~/images/next.png" CommandArgument="Next" CommandName="Page" runat="server" />
                        <asp:ImageButton ImageUrl="~/images/last.png" CommandArgument="Last" CommandName="Page" runat="server" />
                    </td>
                </tr>
            </table>
        </PagerTemplate>
    </asp:GridView>

    Here is another article with example that demonstrate how you can make use of PagerTemplate along with CommandName and CommandArgument: KEY: GridView Paging - Pager Template Example

    Friday, June 2, 2017 7:01 AM
  • User-614943948 posted

    Thanks bro, let me try this thing...

    Friday, June 2, 2017 7:17 AM
  • User-614943948 posted

    It looks pretty good, based on one of your previous answers invoking events of DropDownList when outside the pager template, is easy to invoke. But once it resides inside the pager template, how can I invoke the events and how can I invoke the events of that first, last, previous and next buttons?

    Thanks in Advance

    Friday, June 2, 2017 7:45 AM
  • User-1509636757 posted

    But once it resides inside the pager template, how can I invoke the events and how can I invoke the events of that first, last, previous and next buttons?

    You will still be able to handle event for DropDownList's SelectedIndexChanged event as normal, it is just that you have to get SelectedValue as:

    <asp:DropDownList ID="PageDropDownList"
        AutoPostBack="true"
        OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged"
        runat="server">
        <asp:ListItem>5</asp:ListItem>
        <asp:ListItem>10</asp:ListItem>
        <asp:ListItem>15</asp:ListItem>
        <asp:ListItem>20</asp:ListItem>
    </asp:DropDownList>
    
    
    //-- code behind
    protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
    {
        int pageSize = Convert.ToInt32((sender as DropDownList).SelectedItem.Text);
        grdReport.PageSize = pageSize;
        //-- rebind the grid
    }

    how can I invoke the events and how can I invoke the events of that first, last, previous and next buttons?

    They should invoke RowCommand event of the GridView where you can check for CommandName == Page and based on what is CommandArgument (First, Last, Next or Previous) you can set the GridView PageIndex or do Custom Paging. Here is an example how you can handle this CommandName ("Page") and CommandArgument (First, Last, Next or Previous) using RowCommand: GridView custom pager template in asp.net

    Friday, June 2, 2017 8:57 AM
  • User-614943948 posted

    Thanks Bro. I tried something similar to this and it worked well. Here is my source code.

    <PagerTemplate>
                            <table width="100%">
                                <tr>
                                    <td style="width: 30%">
                                        
                                    </td>
                                    <td style="width:70%"; align="left">
                                        <asp:ImageButton ImageUrl="~/images/first.jpg" CommandArgument="first" CommandName="Page" runat="server" />
                                        <asp:ImageButton ImageUrl="~/images/previous.jpg" CommandArgument="Prev" CommandName="Page" runat="server" />
                                        <asp:DropDownList ID="PageItems" runat="server" ToolTip="Go to Page"
                                            AutoPostBack="true" OnSelectedIndexChanged="PageItems_SelectedIndexChanged" >
                                            <asp:ListItem>5</asp:ListItem>
                                            <asp:ListItem>10</asp:ListItem>
                                            <asp:ListItem>15</asp:ListItem>
                                            <asp:ListItem>20</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:ImageButton ImageUrl="~/images/next.jpg" CommandArgument="next" CommandName="Page" runat="server" />
                                        <asp:ImageButton ImageUrl="~/images/last.jpg" CommandArgument="Last" CommandName="Page" runat="server" />
                                    </td>
                                </tr>
                            </table>
                        </PagerTemplate>
    protected void PageItems_SelectedIndexChanged(object sender, EventArgs e)
            {
                GridViewRow pageRow = grdReport.BottomPagerRow;
    
                // Retrieve the PageDropDownList DropDownList from the bottom pager row.
                DropDownList pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
    
                // Set the PageIndex property to display that page selected by the user.
                grdReport.PageSize = Convert.ToInt16(pageList.SelectedValue);
                GetLoginHistoryDetails(0, grdReport.PageSize);
            }

    There is just one small problem. When change the page size from the dropdown it resets to 5 after the loading the data. I want the selected value to be retained Can you help me in resolving this issue?

    Why is the DropDown resetting?

    Friday, June 2, 2017 9:22 AM
  • User-1509636757 posted

    When change the page size from the dropdown it resets to 5 after the loading the data. I want the selected value to be retained

    That should not happen if you are using UpdatePanels. But, if it does anyhow, then you can simply set it back after binding the GridView as:

    if (ddlPageSize.Items.FindByValue(value.ToString()) != null)
    {
        ddlPageSize.SelectedIndex = -1;
        ddlPageSize.Items.FindByValue(value.ToString()).Selected = true;
    }

    here variable value is used to store value of selected page size; assign value in SelectedIndexChanged event and use it here to reset the DropDownList back to the value.

    Friday, June 2, 2017 9:47 AM
  • User-614943948 posted

    You are right bro. For now I have commented the UpdatePanel I am focusing on the dropdown to change the pages

    Friday, June 2, 2017 10:00 AM
  • User-614943948 posted

    OK I finally decided to implement UpdatePanel which is indeed a very good idea. Now you said that this source code..

    protected void PageItems_SelectedIndexChanged(object sender, EventArgs e)
            {
                GridViewRow pageRow = grdReport.BottomPagerRow;
    
                // Retrieve the PageDropDownList DropDownList from the bottom pager row.
                DropDownList pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
    
                // Set the PageIndex property to display that page selected by the user.
                grdReport.PageSize = Convert.ToInt16(pageList.SelectedValue);
    
                //Bind Grid
                GetLoginHistoryDetails(0, grdReport.PageSize);
    
                if (pageList.Items.FindByValue(pageList.SelectedValue) != null)
                {
                    pageList.SelectedIndex = -1;
                    pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;
                }
            }

    But the result is still the same

    Friday, June 2, 2017 10:58 AM
  • User-1509636757 posted

    if (pageList.Items.FindByValue(pageList.SelectedValue) != null)

    That is strange. Make sure ViewState is not disabled for this page/control. Also, I suggest you put a breakpoint at this line and see if that code really executes.

    Friday, June 2, 2017 11:10 AM
  • User-614943948 posted

    Found the problem. The source code is indeed getting executed.

    if (pageList.Items.FindByValue(pageList.SelectedValue) != null)
                {
                    pageList.SelectedIndex = -1;
                    pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;
                }

    Lets say I changed the value from 5 to 10 in the dropdown. So in the if condition it indeed changes to 10. But in the last statement

    pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;

    It changes back to 5

    This line changes it back to 5

    pageList.SelectedIndex = -1;

    What I think is the DropDownList is recreated after the Grid is reloaded so it might be resetting it

    Friday, June 2, 2017 11:19 AM
  • User-1509636757 posted

    if (pageList.Items.FindByValue(pageList.SelectedValue) != null)
                {
                    pageList.SelectedIndex = -1;
                    pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;
                }

    Do not use pageList.SelectedValue in above if condition. Instead, store the pageList.SelectedValue value in a variable and use that variable in above if condition instead of pageList.SelectedValue. That should resolve.

    Friday, June 2, 2017 11:37 AM
  • User-614943948 posted
    GetLoginHistoryDetails(0, grdReport.PageSize);
    
                string PageCount = pageList.SelectedValue;
                if (pageList.Items.FindByValue(pageList.SelectedValue) != null)
                {
                    pageList.SelectedIndex = -1;
                    //pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;
                    pageList.Items.FindByValue(PageCount).Selected = true;
                }

    Same result. 

    I saw another example where someone implemented it in RowDataBound of the GridView.

    protected void CustomersGridView_DataBound(Object sender, EventArgs e)
        {
            // Retrieve the pager row.
            GridViewRow pagerRow = CustomersGridView.BottomPagerRow;
    
            // Retrieve the DropDownList and Label controls from the row.
            DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
            Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
    
            if (pageList != null)
            {
    
                // Create the values for the DropDownList control based on 
                // the  total number of pages required to display the data
                // source.
                for (int i = 0; i < CustomersGridView.PageCount; i++)
                {
    
                    // Create a ListItem object to represent a page.
                    int pageNumber = i + 1;
                    ListItem item = new ListItem(pageNumber.ToString());
    
                    // If the ListItem object matches the currently selected
                    // page, flag the ListItem object as being selected. Because
                    // the DropDownList control is recreated each time the pager
                    // row gets created, this will persist the selected item in
                    // the DropDownList control.   
                    if (i == CustomersGridView.PageIndex)
                    {
                        item.Selected = true;
                    }
    
                    // Add the ListItem object to the Items collection of the 
                    // DropDownList.
                    pageList.Items.Add(item);
                }
            }
    
            if (pageLabel != null)
            {
                // Calculate the current page number.
                int currentPage = CustomersGridView.PageIndex + 1;
    
                // Update the Label control with the current page information.
                pageLabel.Text = "Page " + currentPage.ToString() +
                  " of " + CustomersGridView.PageCount.ToString();
            }
        }

    Can this solution work for me too?

    Friday, June 2, 2017 11:44 AM
  • User-1509636757 posted

    That is a different code snippet. That is actually DropDown to select on which page you actually wanted to Go.

    can you post your complete code with design?

    Friday, June 2, 2017 12:08 PM
  • User-614943948 posted
    <%@ Page Title="" Language="C#" MasterPageFile="~/StoreMain.Master" AutoEventWireup="true"
        CodeBehind="frmLoginHistory.aspx.cs" Inherits="QuickWeb.Reports.frmLoginHistory" %>
    
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <div id="divShowMsg" class="row-fluid col-sm-12 Textpadding" style="display: none;">
            <div id="DivContainerStatus">
                <div id="DivContainerInnerStatus" class="span label label-default">
                    <h4 class="text-center">
                        <asp:Label ID="lblMsg" runat="server" EnableViewState="False" Font-Bold="True" ForeColor="White"
                            ClientIDMode="Static" />
                    </h4>
                </div>
            </div>
        </div>
        <div class="panel panel-primary ">
            <div class="panel-heading">
                <h3 class="panel-title">Login History Details
                    <div id="reportrange" class="datefilter">
                        <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp;<span id="spnReportDate"
                            runat="server" clientidmode="Static"></span><b class="caret"> </b>
                    </div>
                </h3>
            </div>
            <div class="panel-body">
                <div class="row-fluid">
                    <div class="col-sm-3">
                        <div class="input-group">
                            <span class="input-group-addon IconBkColor"><i class="fa fa-users fa-lg"></i></span>
                            <asp:TextBox ID="txtUserID" runat="server" AutoPostBack="True" onfocus="javascript:select();"
                                MaxLength="100" OnTextChanged="txtUserID_TextChanged" CssClass="form-control"
                                placeholder="Filter by User ID"></asp:TextBox>
                            <cc1:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="txtUserID"
                                ServicePath="~/AutoComplete.asmx" ServiceMethod="GetUserIDCompletionList" MinimumPrefixLength="1"
                                UseContextKey="true" ContextKey="All" CompletionInterval="10" CompletionSetCount="15"
                                FirstRowSelected="True" Enabled="True" CompletionListCssClass="AutoExtender_new"
                                CompletionListItemCssClass="AutoExtenderList_new" CompletionListHighlightedItemCssClass="AutoExtenderHighlight_new">
                            </cc1:AutoCompleteExtender>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="input-group">
                            <span class="input-group-addon IconBkColor"><i class="fa fa-gavel fa-lg"></i></span>
                            <asp:TextBox ID="txtReason" runat="server" AutoPostBack="True" onfocus="javascript:select();"
                                MaxLength="100" OnTextChanged="txtReason_TextChanged" CssClass="form-control"
                                placeholder="Filter by Reason"></asp:TextBox>
                            <cc1:AutoCompleteExtender runat="server" ID="AutoCompleteExtender1" TargetControlID="txtReason"
                                ServicePath="~/AutoComplete.asmx" ServiceMethod="GetReasonList" MinimumPrefixLength="1"
                                UseContextKey="true" ContextKey="All" CompletionInterval="10" CompletionSetCount="15"
                                FirstRowSelected="True" CompletionListCssClass="AutoExtender_new" CompletionListItemCssClass="AutoExtenderList_new"
                                CompletionListHighlightedItemCssClass="AutoExtenderHighlight_new">
                            </cc1:AutoCompleteExtender>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="input-group">
                            <span class="input-group-addon IconBkColor">Status</span>
                            <asp:DropDownList ID="drpActive" runat="server" OnSelectedIndexChanged="drpActive_SelectedIndexChanged"
                                CssClass="form-control" AutoPostBack="true">
                                <asp:ListItem Text="ALL" Value="All" />
                                <asp:ListItem Text="Success" Value="Success" />
                                <asp:ListItem Text="Deny" Value="Deny" />
                            </asp:DropDownList>
                        </div>
                    </div>
                    <div class="col-sm-2 input-group" style="display: none">
                        <asp:LinkButton ID="btnShow" class="btn btn-primary" EnableTheming="false" runat="server"
                            ClientIDMode="Static" Visible="true" OnClick="btnShow_Click"><i class="fa fa-list-alt fa-lg"></i>&nbsp;Show</asp:LinkButton>
                    </div>
                </div>
                <br />
    
                <asp:UpdatePanel runat="server" ID="UpdatePaneilLoginHistory">
                    <ContentTemplate>
                <div class="row-fluid" style="height: 70%; background-color: White; overflow: auto">
                    <asp:GridView ID="grdReport" runat="server" EmptyDataText="No Login history record found."
                        AllowPaging="True" AllowCustomPaging="true"
                        AutoGenerateColumns="False" CssClass="Table Table-striped Table-bordered Table-hover"
                        EnableTheming="False" OnPageIndexChanging="grdReport_PageIndexChanging">
                        <Columns>
                            <asp:BoundField DataField="userid" HeaderText="User ID" />
                            <asp:BoundField DataField="LoginDate" HeaderText="Date" />
                            <asp:BoundField DataField="LoginTime" HeaderText="Time" />
                            <asp:BoundField DataField="Success" HeaderText="Success" />
                            <asp:BoundField DataField="Reason" HeaderText="Reason" />
                        </Columns>
                        <HeaderStyle Font-Size="12px" />
                        <PagerTemplate>
                            <table width="100%">
                                <tr>
                                    <td style="width: 30%">
                                        
                                    </td>
                                    <td style="width:70%"; align="left">
                                        <asp:ImageButton ImageUrl="~/images/first.jpg" CommandArgument="first" CommandName="Page" runat="server" />
                                        <asp:ImageButton ImageUrl="~/images/previous.jpg" CommandArgument="Prev" CommandName="Page" runat="server" />
                                        <asp:DropDownList ID="PageItems" EnableViewState="true" runat="server" ToolTip="Go to Page"
                                            AutoPostBack="true" OnSelectedIndexChanged="PageItems_SelectedIndexChanged" >
                                            <asp:ListItem>5</asp:ListItem>
                                            <asp:ListItem>10</asp:ListItem>
                                            <asp:ListItem>15</asp:ListItem>
                                            <asp:ListItem>20</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:ImageButton ImageUrl="~/images/next.jpg" CommandArgument="next" CommandName="Page" runat="server" />
                                        <asp:ImageButton ImageUrl="~/images/last.jpg" CommandArgument="Last" CommandName="Page" runat="server" />
                                    </td>
                                </tr>
                            </table>
                        </PagerTemplate>
                    </asp:GridView>
                    </ContentTemplate>
                    </asp:UpdatePanel>
                </div>
                <div>
                    <asp:DropDownList ID="pageSize" runat="server" AutoPostBack="true"
                        OnSelectedIndexChanged="pageSize_SelectedIndexChanged">
                        <asp:ListItem>5</asp:ListItem>
                        <asp:ListItem>10</asp:ListItem>
                        <asp:ListItem>15</asp:ListItem>
                        <asp:ListItem>20</asp:ListItem>
                    </asp:DropDownList>
                    <asp:Label ID="NumberOfPages"
                        ForeColor="Blue"
                        Text="Select Page Size"
                        runat="server">
                    </asp:Label> 
                </div>
            </div>
            <div class="panel-footer">
                <asp:LinkButton ID="btnExport" class="btn btn-primary" EnableTheming="false" runat="server"
                    OnClick="btnExport_Click" ClientIDMode="Static" Visible="true"><i class="fa fa-file-excel-o"></i> Export to Excel</asp:LinkButton>
            </div>
            <asp:HiddenField ID="hdnDateFromAndTo" runat="server" ClientIDMode="Static" />
        </div>
        <script type="text/javascript">
            function setDivMouseOver(argColorOne, argColorTwo) {
                document.getElementById('divShowMsg').style.display = "inline";
                $('#DivContainerInnerStatus').css('backgroundColor', argColorOne);
                setTimeout(function () { $('#divShowMsg').fadeOut(3000); }, 4000);
            }
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                var cb = function (start, end, label) {
                    console.log(start.toISOString(), end.toISOString(), label);
                    $('#reportrange span').html(start.format('DD MMM YYYY') + ' - ' + end.format('DD MMM YYYY'));
                    $('#hdnDateFromAndTo').val($('#spnReportDate').text());
                    document.getElementById("<%=btnShow.ClientID %>").click();
                }
                var strTmpDate = $('#hdnDateFromAndTo').val().split('-');
                var optionSet1 = {
                    startDate: moment(strTmpDate[0]),
                    endDate: moment(strTmpDate[1]),
                    minDate: '01/01/2010',
                    maxDate: '12/31/2050',
                    // dateLimit: { days: 60 },
                    showDropdowns: true,
                    showWeekNumbers: true,
                    timePicker: false,
                    timePickerIncrement: 1,
                    timePicker12Hour: true,
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    },
                    opens: 'left',
                    buttonClasses: ['btn btn-default'],
                    applyClass: 'btn-small btn-primary',
                    cancelClass: 'btn-small',
                    format: 'MM/DD/YYYY',
                    separator: ' to ',
                    locale: {
                        applyLabel: 'Submit',
                        cancelLabel: 'Clear',
                        fromLabel: 'From',
                        toLabel: 'To',
                        customRangeLabel: 'Date Range',
                        daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                        firstDay: 1
                    }
                };
                var optionSet2 = {
                    startDate: moment().subtract(7, 'days'),
                    endDate: moment(),
                    opens: 'left',
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    }
                };
                $('#reportrange span').html($('#hdnDateFromAndTo').val());
                $('#reportrange').daterangepicker(optionSet1, cb);
    
                $('#reportrange').on('show.daterangepicker', function () { console.log("show event fired"); });
                $('#reportrange').on('hide.daterangepicker', function () { console.log("hide event fired"); });
                $('#reportrange').on('apply.daterangepicker', function (ev, picker) {
                    console.log("apply event fired, start/end dates are "
                          + picker.startDate.format('MMMM D, YYYY')
                          + " to "
                          + picker.endDate.format('MMMM D, YYYY')
                        );
                });
                $('#reportrange').on('cancel.daterangepicker', function (ev, picker) { console.log("cancel event fired"); });
    
                $('#options1').click(function () {
                    $('#reportrange').data('daterangepicker').setOptions(optionSet1, cb);
                });
    
                $('#options2').click(function () {
                    $('#reportrange').data('daterangepicker').setOptions(optionSet2, cb);
                });
    
                $('#destroy').click(function () {
                    $('#reportrange').data('daterangepicker').remove();
                });
            });
        </script>
    </asp:Content>
    
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Text;
    using System.IO;
    using System.Data.SqlClient;
    
    namespace QuickWeb.Reports
    {
        public partial class frmLoginHistory : System.Web.UI.Page
        {
            public static string strFromDate = string.Empty, strToDate = string.Empty;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    setAutoCompleteExtenderServicePath();
                    ArrayList date = new ArrayList();
                    date = DAL.DALFactory.Instance.DAL_DateAndTime.getDateAndTimeAccordingToZoneTime(Globals.BranchID);
                    hdnDateFromAndTo.Value = date[0].ToString() + " - " + date[0].ToString();               
                    txtUserID.Focus();
                    btnExport.Visible = false;
    
                    grdReport.PageSize = Convert.ToInt16(pageSize.SelectedValue);
                    grdReport.VirtualItemCount = GetLoginHistoryCount();
                    GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
                    //BindGrid();
                }
            }
    
            protected void txtUserID_TextChanged(object sender, EventArgs e)
            {
                try
                {
                  txtReason.Text = "";
                  BindGrid();
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ScriptRegistration", "setDivMouseOver('Red', '#999999');", true);             
                    lblMsg.Text = "Please enter valid UserID.";
                    txtUserID.Focus();
                    txtUserID.Attributes.Add("onfocus", "javascript:select();");
                }
            }
    
            private Int32 GetLoginHistoryCount()
            {
                var DateFromAndTo = hdnDateFromAndTo.Value.Split('-');
    
                strFromDate = DateFromAndTo[0].Trim();
                strToDate = DateFromAndTo[1].Trim();
    
                return Convert.ToInt32(BAL.BALFactory.Instance.BL_CustomerMaster.LoginHistoryCount(strFromDate, strToDate, txtUserID.Text, txtReason.Text, drpActive.SelectedValue, Globals.BranchID));
            }
            private void BindGrid()
            {
    
                grdReport.DataSource = null;
                grdReport.DataBind();
    
                var DateFromAndTo = hdnDateFromAndTo.Value.Split('-');
    
                strFromDate = DateFromAndTo[0].Trim();
                strToDate = DateFromAndTo[1].Trim();
    
                grdReport.DataSource = BAL.BALFactory.Instance.BL_CustomerMaster.BindGridLoginHistory(strFromDate, strToDate, txtUserID.Text, txtReason.Text, drpActive.SelectedValue, Globals.BranchID);
                grdReport.DataBind();
    
                bool blnRight = AppClass.CheckExportToExcelRightOnPage();
                if (blnRight)
                {
                    btnExport.Visible = true;
                    if (grdReport.Rows.Count > 0)
                    {
                        btnExport.Visible = true;
                    }
                    else
                    {
                        btnExport.Visible = false;
                    }
                }
                else
                {
                    btnExport.Visible = false;
                }
    
            }
            protected void btnShow_Click(object sender, EventArgs e)
            {
                //BindGrid();
                grdReport.VirtualItemCount = GetLoginHistoryCount();
                GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
            }
            protected void drpActive_SelectedIndexChanged(object sender, EventArgs e)
            {
                //BindGrid();
                grdReport.VirtualItemCount = GetLoginHistoryCount();
                GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
            }
    
            protected void btnExport_Click(object sender, EventArgs e)
            {
                string strFileName = "strReportFile.xls";
                Response.Expires = 0;
                Response.Buffer = true;
                GridView grd = new GridView();
                grd.DataSource = (DataSet)ViewState["SavedDS"];
                grd.DataBind();
                StringBuilder strDataToSaveInFile = AppClass.GetExcelContentForGridBookingNew(grdReport, strFromDate, strToDate, "Log History Report", false);
                string strFilePathToSave = "";
                Response.ContentType = "application/vnd.ms-excel";
                strFilePathToSave = "~/Docs/" + strFileName;
                StreamWriter StreamWriter1 = new StreamWriter(Server.MapPath(strFilePathToSave));
                StreamWriter1.Write(strDataToSaveInFile);
                StreamWriter1.Close();
                Response.AddHeader("Content-Disposition", "inline; filename=" + strFileName);
                Response.Redirect(strFilePathToSave + "?ClearContent=" + DateTime.Now.ToString(), false);
            }
            protected void txtReason_TextChanged(object sender, EventArgs e)
            {
                try
                {
                    txtUserID.Text = "";
                    BindGrid();
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ScriptRegistration", "setDivMouseOver('Red', '#999999');", true);
                    lblMsg.Text = "Please enter valid reason.";
                    txtReason.Focus();
                    txtReason.Attributes.Add("onfocus", "javascript:select();");
                }
            }
    
            /// <summary>
            /// Created by Adeel on June 1, 2017 for custom paging
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void grdReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                grdReport.PageIndex = e.NewPageIndex;
                GetLoginHistoryDetails(e.NewPageIndex, Convert.ToInt16(pageSize.SelectedValue));
            }
    
            protected void pageSize_SelectedIndexChanged(object sender, EventArgs e)
            {
                grdReport.PageSize = Convert.ToInt16(pageSize.SelectedValue);
                GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
            }
    
            protected void PageItems_SelectedIndexChanged(object sender, EventArgs e)
            {
                GridViewRow pageRow = grdReport.BottomPagerRow;
    
                // Retrieve the PageDropDownList DropDownList from the bottom pager row.
                DropDownList pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
    
                // Set the PageIndex property to display that page selected by the user.
                grdReport.PageSize = Convert.ToInt16(pageList.SelectedValue);
    
                //Bind Grid
                GetLoginHistoryDetails(0, grdReport.PageSize);
    
                string PageCount = pageList.SelectedValue;
                if (pageList.Items.FindByValue(pageList.SelectedValue) != null)
                {
                    pageList.SelectedIndex = -1;
                    //pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;
                    pageList.Items.FindByValue(PageCount).Selected = true;
                }
            }
    
            /// <summary>
            /// Created by Adeel on June1, 2017 to for custom paging
            /// </summary>
            /// <param name="CurrentPage"></param>
            /// <param name="PageSize"></param>
            private void GetLoginHistoryDetails(int CurrentPage, int PageSize)
            {
                grdReport.DataSource = null;
                grdReport.DataBind();
    
                var DateFromAndTo = hdnDateFromAndTo.Value.Split('-');
    
                strFromDate = DateFromAndTo[0].Trim();
                strToDate = DateFromAndTo[1].Trim();
    
                grdReport.DataSource = BAL.BALFactory.Instance.BL_CustomerMaster.BindGridLoginHistory_V2(PageSize, CurrentPage, strFromDate, strToDate, txtUserID.Text, txtReason.Text, drpActive.SelectedValue, Globals.BranchID);
                grdReport.DataBind();
    
                bool blnRight = AppClass.CheckExportToExcelRightOnPage();
                if (blnRight)
                {
                    btnExport.Visible = true;
                    if (grdReport.Rows.Count > 0)
                    {
                        btnExport.Visible = true;
                    }
                    else
                    {
                        btnExport.Visible = false;
                    }
                }
                else
                {
                    btnExport.Visible = false;
                }
    
            }
                    
            public void setAutoCompleteExtenderServicePath()
            {
                try
                {
                    string storeCode = AppClass.GetStoreCodeByPath(HttpContext.Current.Request.RawUrl.ToString());
                    autoComplete1.ServicePath = ResolveUrl(autoComplete1.ServicePath.Replace("~/", ("~/" + storeCode)));
                    AutoCompleteExtender1.ServicePath = ResolveUrl(AutoCompleteExtender1.ServicePath.Replace("~/", ("~/" + storeCode)));
                }
                catch (Exception ex)
                { }
            }
        }
    }


    Please ignore BindGrid function. Its an old function that doesn't uses pagination

    Friday, June 2, 2017 12:33 PM
  • User-1509636757 posted

    Try modifying SelectedIndexChanged event as:

    protected void PageItems_SelectedIndexChanged(object sender, EventArgs e)
    {
        string PageCount = pageList.SelectedValue;
    
        GridViewRow pageRow = grdReport.BottomPagerRow;
    
        // Retrieve the PageDropDownList DropDownList from the bottom pager row.
        DropDownList pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
    
        // Set the PageIndex property to display that page selected by the user.
        grdReport.PageSize = Convert.ToInt16(pageList.SelectedValue);
    
        //Bind Grid
        GetLoginHistoryDetails(0, grdReport.PageSize);
    
        if (pageList.Items.FindByText(PageCount) != null)
        {
            pageList.SelectedIndex = -1;
            pageList.Items.FindByText(PageCount).Selected = true;
        }
    }

    Monday, June 5, 2017 3:19 AM
  • User-614943948 posted

    Still didn't help do you have skype? If you want I can share you my screen using teamviewer

    Monday, June 5, 2017 5:43 AM
  • User-1509636757 posted

    What value you receive in pageCount variable when you are at this line?

    pageList.Items.FindByText(PageCount).Selected = true;
    Monday, June 5, 2017 6:57 AM
  • User-614943948 posted

    It shows the value that I have selected from the dropdown

    Monday, June 5, 2017 7:06 AM
  • User-1509636757 posted

    It shows the value that I have selected from the dropdown

    if that shows the value that you have selected then are you 100% sure that this code is being executed (check in debugging):

    pageList.Items.FindByText(PageCount).Selected = true;

    are you not getting null for pageList.Items.FindByText(PageCount) ?

    Monday, June 5, 2017 7:57 AM
  • User-614943948 posted

    Yes. It is successfully getting executed. No error, no exception

    Monday, June 5, 2017 8:17 AM
  • User-1509636757 posted

    Yes. It is successfully getting executed. No error, no exception

    If you are using UpdatePanel (seems like you are using based on your code posted) then Make sure the Paging DropDownList is inside UpdatePanel. It is very critical if you are using UpdatePanel, otherwise even if you are setting values (like it is happening right now); you won't get updated/refreshed on screen

    Monday, June 5, 2017 8:25 AM
  • User-614943948 posted

    The grid resides inside the update panel. The dropdown resides the PagerTemplate of the grid. So it is inside the update panel.

    <asp:UpdatePanel runat="server" ID="UpdatePaneilLoginHistory">
                    <ContentTemplate>
                        <div class="row-fluid" style="height: 70%; background-color: White; overflow: auto">
                            <asp:GridView ID="grdReport" runat="server" EmptyDataText="No Login history record found."
                                AllowPaging="True" AllowCustomPaging="true" OnDataBound="grdReport_DataBound"
                                AutoGenerateColumns="False" CssClass="Table Table-striped Table-bordered Table-hover"
                                EnableTheming="False" OnPageIndexChanging="grdReport_PageIndexChanging">
                                <Columns>
                                    <asp:BoundField DataField="userid" HeaderText="User ID" />
                                    <asp:BoundField DataField="LoginDate" HeaderText="Date" />
                                    <asp:BoundField DataField="LoginTime" HeaderText="Time" />
                                    <asp:BoundField DataField="Success" HeaderText="Success" />
                                    <asp:BoundField DataField="Reason" HeaderText="Reason" />
                                </Columns>
                                <HeaderStyle Font-Size="12px" />
                                <PagerStyle CssClass="paging" />
                                <PagerTemplate>
                                    <pagerstyle backcolor="#999999" forecolor="Black" horizontalalign="Center" />
                                    <selectedrowstyle backcolor="#008A8C" font-bold="True" forecolor="White" />
                                    <headerstyle backcolor="#000084" font-bold="True" forecolor="White" />
                                    <alternatingrowstyle backcolor="#DCDCDC" />
                                    <table width="100%">
                                        <tr>
                                            <td style="width: 30%">
                                        
                                            </td>
                                            <td style="width:70%"; align="left">
                                                <asp:ImageButton ImageUrl="~/images/first.jpg" CommandArgument="first" CommandName="Page" runat="server" />
                                                <asp:ImageButton ImageUrl="~/images/previous.jpg" CommandArgument="Prev" CommandName="Page" runat="server" />
                                                <asp:DropDownList ID="PageItems" EnableViewState="true" runat="server" ToolTip="Go to Page"
                                                    AutoPostBack="true" OnSelectedIndexChanged="PageItems_SelectedIndexChanged" >
                                                    <asp:ListItem>5</asp:ListItem>
                                                    <asp:ListItem>10</asp:ListItem>
                                                    <asp:ListItem>15</asp:ListItem>
                                                    <asp:ListItem>20</asp:ListItem>
                                                </asp:DropDownList>
                                                <asp:ImageButton ImageUrl="~/images/next.jpg" CommandArgument="next" CommandName="Page" runat="server" />
                                                <asp:ImageButton ImageUrl="~/images/last.jpg" CommandArgument="Last" CommandName="Page" runat="server" />
                                            </td>
                                        </tr>
                                    </table>
                                </PagerTemplate>
                                <%--<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Left" />
                                <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                                <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                                <AlternatingRowStyle BackColor="#DCDCDC" />--%>
                            </asp:GridView>
                        </div>
                        <div>
                            <asp:DropDownList ID="pageSize" runat="server" AutoPostBack="true"
                                OnSelectedIndexChanged="pageSize_SelectedIndexChanged">
                                <asp:ListItem>10</asp:ListItem>
                                <asp:ListItem>15</asp:ListItem>
                                <asp:ListItem>20</asp:ListItem>
                                <asp:ListItem>25</asp:ListItem>
                            </asp:DropDownList>
                        </div>
                    </ContentTemplate>
                </asp:UpdatePanel>

    Monday, June 5, 2017 8:31 AM
  • User-1509636757 posted

    I was able to reproduce the issue when I used your code. And I believe here is the thing: when GridView is rebind from PageItems_SelectedIndexChanged event; even PagerTemplate will also get rebinded; because it is inside the GridView; so you will require to take reference of the DropDownList again, after call to GetLoginHistoryDetails(0, grdReport.PageSize); and then reassign SelectedValue. This will work.

    Another issue I found is; you have two DropDownList in your code; one is inside and other is outside PagerTemplate. I suggest if you are not using outside Pager DropDownList then remove it; because Code is actually using it at several places and that makes it confusive. Here, I am posting my variation of code, in which I guess important change done is inside PageItems_SelectedIndexChanged event:

    public partial class WebForm197 : System.Web.UI.Page
    {
        public static string strFromDate = string.Empty, strToDate = string.Empty;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //setAutoCompleteExtenderServicePath();
                //ArrayList date = new ArrayList();
                //date = DAL.DALFactory.Instance.DAL_DateAndTime.getDateAndTimeAccordingToZoneTime(Globals.BranchID);
                //hdnDateFromAndTo.Value = date[0].ToString() + " - " + date[0].ToString();
                //txtUserID.Focus();
                //btnExport.Visible = false;
    
                grdReport.PageSize = 5;//-- Convert.ToInt16(pageSize.SelectedValue);
                grdReport.VirtualItemCount = GetLoginHistoryCount();
                GetLoginHistoryDetails(0, 5);//--Convert.ToInt16(pageSize.SelectedValue)
                //BindGrid();
            }
        }
    
        protected void txtUserID_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtReason.Text = "";
                BindGrid();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ScriptRegistration", "setDivMouseOver('Red', '#999999');", true);
                lblMsg.Text = "Please enter valid UserID.";
                txtUserID.Focus();
                txtUserID.Attributes.Add("onfocus", "javascript:select();");
            }
        }
    
        private Int32 GetLoginHistoryCount()
        {
            //var DateFromAndTo = hdnDateFromAndTo.Value.Split('-');
    
            //strFromDate = DateFromAndTo[0].Trim();
            //strToDate = DateFromAndTo[1].Trim();
    
            return 15;// Convert.ToInt32(BAL.BALFactory.Instance.BL_CustomerMaster.LoginHistoryCount(strFromDate, strToDate, txtUserID.Text, txtReason.Text, drpActive.SelectedValue, Globals.BranchID));
        }
    
        private void BindGrid()
        {
            grdReport.DataSource = null;
            grdReport.DataBind();
    
            var DateFromAndTo = hdnDateFromAndTo.Value.Split('-');
    
            strFromDate = DateFromAndTo[0].Trim();
            strToDate = DateFromAndTo[1].Trim();
    
            grdReport.DataSource = GetData();// BAL.BALFactory.Instance.BL_CustomerMaster.BindGridLoginHistory(strFromDate, strToDate, txtUserID.Text, txtReason.Text, drpActive.SelectedValue, Globals.BranchID);
            grdReport.DataBind();
    
            //bool blnRight = AppClass.CheckExportToExcelRightOnPage();
            //if (blnRight)
            //{
            //    btnExport.Visible = true;
            //    if (grdReport.Rows.Count > 0)
            //    {
            //        btnExport.Visible = true;
            //    }
            //    else
            //    {
            //        btnExport.Visible = false;
            //    }
            //}
            //else
            //{
            //    btnExport.Visible = false;
            //}
        }
    
        protected void btnShow_Click(object sender, EventArgs e)
        {
            //BindGrid();
            grdReport.VirtualItemCount = GetLoginHistoryCount();
            // GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
        }
    
        protected void drpActive_SelectedIndexChanged(object sender, EventArgs e)
        {
            //BindGrid();
            grdReport.VirtualItemCount = GetLoginHistoryCount();
            // GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
        }
    
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //string strFileName = "strReportFile.xls";
            //Response.Expires = 0;
            //Response.Buffer = true;
            //GridView grd = new GridView();
            //grd.DataSource = (DataSet)ViewState["SavedDS"];
            //grd.DataBind();
            //StringBuilder strDataToSaveInFile = AppClass.GetExcelContentForGridBookingNew(grdReport, strFromDate, strToDate, "Log History Report", false);
            //string strFilePathToSave = "";
            //Response.ContentType = "application/vnd.ms-excel";
            //strFilePathToSave = "~/Docs/" + strFileName;
            //StreamWriter StreamWriter1 = new StreamWriter(Server.MapPath(strFilePathToSave));
            //StreamWriter1.Write(strDataToSaveInFile);
            //StreamWriter1.Close();
            //Response.AddHeader("Content-Disposition", "inline; filename=" + strFileName);
            //Response.Redirect(strFilePathToSave + "?ClearContent=" + DateTime.Now.ToString(), false);
        }
    
        protected void txtReason_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtUserID.Text = "";
                BindGrid();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ScriptRegistration", "setDivMouseOver('Red', '#999999');", true);
                lblMsg.Text = "Please enter valid reason.";
                txtReason.Focus();
                txtReason.Attributes.Add("onfocus", "javascript:select();");
            }
        }
    
        /// <summary>
        /// Created by Adeel on June 1, 2017 for custom paging
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridViewRow pageRow = grdReport.BottomPagerRow;
    
            // Retrieve the PageDropDownList DropDownList from the bottom pager row.
            DropDownList pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
    
            grdReport.PageIndex = e.NewPageIndex;
            GetLoginHistoryDetails(e.NewPageIndex, Convert.ToInt16(pageList.SelectedValue));
        }
    
        //protected void pageSize_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    grdReport.PageSize = Convert.ToInt16(pageSize.SelectedValue);
        //    GetLoginHistoryDetails(0, Convert.ToInt16(pageSize.SelectedValue));
        //}
    
        protected void PageItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow pageRow = grdReport.BottomPagerRow;
                
            // Retrieve the PageDropDownList DropDownList from the bottom pager row.
            DropDownList pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
            string PageCount = pageList.SelectedValue;
    
            // Set the PageIndex property to display that page selected by the user.
            grdReport.PageSize = Convert.ToInt16(pageList.SelectedValue);
    
            //Bind Grid
            GetLoginHistoryDetails(0, grdReport.PageSize);
    
            //-- this is very important:: re-take the reference of pager template to get the dropdownlist
            //-- this is very important:: re-take the reference of pager template to get the dropdownlist
            pageRow = grdReport.BottomPagerRow;
            pageList = (DropDownList)pageRow.Cells[0].FindControl("PageItems");
            if (pageList.Items.FindByText(PageCount) != null)
            {
                pageList.SelectedIndex = -1;
                //pageList.Items.FindByValue(pageList.SelectedValue).Selected = true;
                pageList.Items.FindByText(PageCount).Selected = true;
            }
            //-- this is very important:: re-take the reference of pager template to get the dropdownlist
            //-- this is very important:: re-take the reference of pager template to get the dropdownlist
        }
    
        /// <summary>
        /// Created by Adeel on June1, 2017 to for custom paging
        /// </summary>
        /// <param name="CurrentPage"></param>
        /// <param name="PageSize"></param>
        private void GetLoginHistoryDetails(int CurrentPage, int PageSize)
        {
            //grdReport.DataSource = null;
            //grdReport.DataBind();
    
            //var DateFromAndTo = hdnDateFromAndTo.Value.Split('-');
    
            //strFromDate = DateFromAndTo[0].Trim();
            //strToDate = DateFromAndTo[1].Trim();
    
            grdReport.DataSource = GetData();// BAL.BALFactory.Instance.BL_CustomerMaster.BindGridLoginHistory_V2(PageSize, CurrentPage, strFromDate, strToDate, txtUserID.Text, txtReason.Text, drpActive.SelectedValue, Globals.BranchID);
            grdReport.DataBind();
    
            //bool blnRight = AppClass.CheckExportToExcelRightOnPage();
            //if (blnRight)
            //{
            //    btnExport.Visible = true;
            //    if (grdReport.Rows.Count > 0)
            //    {
            //        btnExport.Visible = true;
            //    }
            //    else
            //    {
            //        btnExport.Visible = false;
            //    }
            //}
            //else
            //{
            //    btnExport.Visible = false;
            //}
        }
    
        private List<LoginData> GetData()
        {
            List<LoginData> data = new List<LoginData>();
            data.Add(new LoginData() { userid = 1 });
            data.Add(new LoginData() { userid = 2 });
            data.Add(new LoginData() { userid = 3 });
            data.Add(new LoginData() { userid = 4 });
            data.Add(new LoginData() { userid = 5 });
            data.Add(new LoginData() { userid = 6 });
            data.Add(new LoginData() { userid = 7 });
            data.Add(new LoginData() { userid = 8 });
            data.Add(new LoginData() { userid = 9 });
            data.Add(new LoginData() { userid = 10 });
            data.Add(new LoginData() { userid = 11 });
            data.Add(new LoginData() { userid = 12 });
            data.Add(new LoginData() { userid = 13 });
            data.Add(new LoginData() { userid = 14 });
            data.Add(new LoginData() { userid = 15 });
            return data;
        }
    
        public void setAutoCompleteExtenderServicePath()
        {
            try
            {
                //string storeCode = AppClass.GetStoreCodeByPath(HttpContext.Current.Request.RawUrl.ToString());
                //autoComplete1.ServicePath = ResolveUrl(autoComplete1.ServicePath.Replace("~/", ("~/" + storeCode)));
                //AutoCompleteExtender1.ServicePath = ResolveUrl(AutoCompleteExtender1.ServicePath.Replace("~/", ("~/" + storeCode)));
            }
            catch (Exception ex)
            { }
        }
    }
    
    public class LoginData
    {
        public int userid { get; set; }
    }
            <asp:ScriptManager runat="server" />
            <div id="divShowMsg" class="row-fluid col-sm-12 Textpadding" style="display: none;">
            <div id="DivContainerStatus">
                <div id="DivContainerInnerStatus" class="span label label-default">
                    <h4 class="text-center">
                        <asp:Label ID="lblMsg" runat="server" EnableViewState="False" Font-Bold="True" ForeColor="White"
                            ClientIDMode="Static" />
                    </h4>
                </div>
            </div>
        </div>
        <div class="panel panel-primary ">
            <div class="panel-heading">
                <h3 class="panel-title">Login History Details
                    <div id="reportrange" class="datefilter">
                        <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp;<span id="spnReportDate"
                            runat="server" clientidmode="Static"></span><b class="caret"> </b>
                    </div>
                </h3>
            </div>
            <div class="panel-body">
                <div class="row-fluid">
                    <div class="col-sm-3">
                        <div class="input-group">
                            <span class="input-group-addon IconBkColor"><i class="fa fa-users fa-lg"></i></span>
                            <asp:TextBox ID="txtUserID" runat="server" AutoPostBack="True" onfocus="javascript:select();"
                                MaxLength="100" OnTextChanged="txtUserID_TextChanged" CssClass="form-control"
                                placeholder="Filter by User ID"></asp:TextBox>
                            <ajaxToolkit:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="txtUserID"
                                ServicePath="~/AutoComplete.asmx" ServiceMethod="GetUserIDCompletionList" MinimumPrefixLength="1"
                                UseContextKey="true" ContextKey="All" CompletionInterval="10" CompletionSetCount="15"
                                FirstRowSelected="True" Enabled="True" CompletionListCssClass="AutoExtender_new"
                                CompletionListItemCssClass="AutoExtenderList_new" CompletionListHighlightedItemCssClass="AutoExtenderHighlight_new">
                            </ajaxToolkit:AutoCompleteExtender>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="input-group">
                            <span class="input-group-addon IconBkColor"><i class="fa fa-gavel fa-lg"></i></span>
                            <asp:TextBox ID="txtReason" runat="server" AutoPostBack="True" onfocus="javascript:select();"
                                MaxLength="100" OnTextChanged="txtReason_TextChanged" CssClass="form-control"
                                placeholder="Filter by Reason"></asp:TextBox>
                            <ajaxToolkit:AutoCompleteExtender runat="server" ID="AutoCompleteExtender1" TargetControlID="txtReason"
                                ServicePath="~/AutoComplete.asmx" ServiceMethod="GetReasonList" MinimumPrefixLength="1"
                                UseContextKey="true" ContextKey="All" CompletionInterval="10" CompletionSetCount="15"
                                FirstRowSelected="True" CompletionListCssClass="AutoExtender_new" CompletionListItemCssClass="AutoExtenderList_new"
                                CompletionListHighlightedItemCssClass="AutoExtenderHighlight_new">
                            </ajaxToolkit:AutoCompleteExtender>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="input-group">
                            <span class="input-group-addon IconBkColor">Status</span>
                            <asp:DropDownList ID="drpActive" runat="server" OnSelectedIndexChanged="drpActive_SelectedIndexChanged"
                                CssClass="form-control" AutoPostBack="true">
                                <asp:ListItem Text="ALL" Value="All" />
                                <asp:ListItem Text="Success" Value="Success" />
                                <asp:ListItem Text="Deny" Value="Deny" />
                            </asp:DropDownList>
                        </div>
                    </div>
                    <div class="col-sm-2 input-group" style="display: none">
                        <asp:LinkButton ID="btnShow" class="btn btn-primary" EnableTheming="false" runat="server"
                            ClientIDMode="Static" Visible="true" OnClick="btnShow_Click"><i class="fa fa-list-alt fa-lg"></i>&nbsp;Show</asp:LinkButton>
                    </div>
                </div>
                <br />
    
                <asp:UpdatePanel runat="server" ID="UpdatePaneilLoginHistory">
                    <ContentTemplate>
                <div class="row-fluid" style="height: 70%; background-color: White; overflow: auto">
                    <asp:GridView ID="grdReport" runat="server" EmptyDataText="No Login history record found."
                        AllowPaging="True" AllowCustomPaging="true"
                        AutoGenerateColumns="False" CssClass="Table Table-striped Table-bordered Table-hover"
                        EnableTheming="False" OnPageIndexChanging="grdReport_PageIndexChanging">
                        <Columns>
                            <asp:BoundField DataField="userid" HeaderText="User ID" />
                            <%--<asp:BoundField DataField="LoginDate" HeaderText="Date" />
                            <asp:BoundField DataField="LoginTime" HeaderText="Time" />
                            <asp:BoundField DataField="Success" HeaderText="Success" />
                            <asp:BoundField DataField="Reason" HeaderText="Reason" />--%>
                        </Columns>
                        <HeaderStyle Font-Size="12px" />
                        <PagerTemplate>
                            <table width="100%">
                                <tr>
                                    <td style="width: 30%">
                                    </td>
                                    <td style="width:70%"; align="left">
                                        <asp:ImageButton ImageUrl="~/images/first.jpg" CommandArgument="first" CommandName="Page" runat="server" />
                                        <asp:ImageButton ImageUrl="~/images/previous.jpg" CommandArgument="Prev" CommandName="Page" runat="server" />
                                        <asp:DropDownList ID="PageItems" EnableViewState="true" runat="server" ToolTip="Go to Page"
                                            AutoPostBack="true" OnSelectedIndexChanged="PageItems_SelectedIndexChanged">
                                            <asp:ListItem>5</asp:ListItem>
                                            <asp:ListItem>10</asp:ListItem>
                                            <asp:ListItem>15</asp:ListItem>
                                            <asp:ListItem>20</asp:ListItem>
                                        </asp:DropDownList>
                                        <asp:ImageButton ImageUrl="~/images/next.jpg" CommandArgument="next" CommandName="Page" runat="server" />
                                        <asp:ImageButton ImageUrl="~/images/last.jpg" CommandArgument="Last" CommandName="Page" runat="server" />
                                    </td>
                                </tr>
                            </table>
                        </PagerTemplate>
                    </asp:GridView>
                    </ContentTemplate>
                    </asp:UpdatePanel>
                </div>
               <%-- <div>
                    <asp:DropDownList ID="pageSize" runat="server" AutoPostBack="true"
                        OnSelectedIndexChanged="pageSize_SelectedIndexChanged">
                        <asp:ListItem>5</asp:ListItem>
                        <asp:ListItem>10</asp:ListItem>
                        <asp:ListItem>15</asp:ListItem>
                        <asp:ListItem>20</asp:ListItem>
                    </asp:DropDownList>
                    <asp:Label ID="NumberOfPages"
                        ForeColor="Blue"
                        Text="Select Page Size"
                        runat="server">
                    </asp:Label>
                </div>--%>
            </div>
            <div class="panel-footer">
                <asp:LinkButton ID="btnExport" class="btn btn-primary" EnableTheming="false" runat="server"
                    OnClick="btnExport_Click" ClientIDMode="Static" Visible="true"><i class="fa fa-file-excel-o"></i> Export to Excel</asp:LinkButton>
            </div>
            <asp:HiddenField ID="hdnDateFromAndTo" runat="server" ClientIDMode="Static" />
        </div>
        <script type="text/javascript">
            function setDivMouseOver(argColorOne, argColorTwo) {
                document.getElementById('divShowMsg').style.display = "inline";
                $('#DivContainerInnerStatus').css('backgroundColor', argColorOne);
                setTimeout(function () { $('#divShowMsg').fadeOut(3000); }, 4000);
            }
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                var cb = function (start, end, label) {
                    console.log(start.toISOString(), end.toISOString(), label);
                    $('#reportrange span').html(start.format('DD MMM YYYY') + ' - ' + end.format('DD MMM YYYY'));
                    $('#hdnDateFromAndTo').val($('#spnReportDate').text());
                    document.getElementById("<%=btnShow.ClientID %>").click();
                }
                var strTmpDate = $('#hdnDateFromAndTo').val().split('-');
                var optionSet1 = {
                    startDate: moment(strTmpDate[0]),
                    endDate: moment(strTmpDate[1]),
                    minDate: '01/01/2010',
                    maxDate: '12/31/2050',
                    // dateLimit: { days: 60 },
                    showDropdowns: true,
                    showWeekNumbers: true,
                    timePicker: false,
                    timePickerIncrement: 1,
                    timePicker12Hour: true,
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    },
                    opens: 'left',
                    buttonClasses: ['btn btn-default'],
                    applyClass: 'btn-small btn-primary',
                    cancelClass: 'btn-small',
                    format: 'MM/DD/YYYY',
                    separator: ' to ',
                    locale: {
                        applyLabel: 'Submit',
                        cancelLabel: 'Clear',
                        fromLabel: 'From',
                        toLabel: 'To',
                        customRangeLabel: 'Date Range',
                        daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                        firstDay: 1
                    }
                };
                var optionSet2 = {
                    startDate: moment().subtract(7, 'days'),
                    endDate: moment(),
                    opens: 'left',
                    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    }
                };
                $('#reportrange span').html($('#hdnDateFromAndTo').val());
                $('#reportrange').daterangepicker(optionSet1, cb);
    
                $('#reportrange').on('show.daterangepicker', function () { console.log("show event fired"); });
                $('#reportrange').on('hide.daterangepicker', function () { console.log("hide event fired"); });
                $('#reportrange').on('apply.daterangepicker', function (ev, picker) {
                    console.log("apply event fired, start/end dates are "
                        + picker.startDate.format('MMMM D, YYYY')
                        + " to "
                        + picker.endDate.format('MMMM D, YYYY')
                    );
                });
                $('#reportrange').on('cancel.daterangepicker', function (ev, picker) { console.log("cancel event fired"); });
    
                $('#options1').click(function () {
                    $('#reportrange').data('daterangepicker').setOptions(optionSet1, cb);
                });
    
                $('#options2').click(function () {
                    $('#reportrange').data('daterangepicker').setOptions(optionSet2, cb);
                });
    
                $('#destroy').click(function () {
                    $('#reportrange').data('daterangepicker').remove();
                });
            });
        </script>



    Monday, June 5, 2017 9:53 AM
  • User-614943948 posted

    Thank you Bro. I will try this and let you know. The reason I used 2 DropDown list is, until the list that resides in the grid doesn't work, I had to use the one outside

    Monday, June 5, 2017 10:36 AM
  • User-614943948 posted

    Thanks bro, it worked. My last question, adding this page template, removed the page numbers that were getting displayed for paging.

    <PagerTemplate>
                                    <table width="100%">
                                        <tr>
                                            <td style="width:70%"; align="left">
                                                <asp:DropDownList ID="PageItems" EnableViewState="true" runat="server" ToolTip="Go to Page"
                                                    AutoPostBack="true" OnSelectedIndexChanged="PageItems_SelectedIndexChanged" >
                                                    <asp:ListItem>10</asp:ListItem>
                                                    <asp:ListItem>15</asp:ListItem>
                                                    <asp:ListItem>20</asp:ListItem>
                                                    <asp:ListItem>25</asp:ListItem>
                                                </asp:DropDownList>
                                            </td>
                                        </tr>
                                    </table>
                                </PagerTemplate>

    Is there a way I can get those page numbers back

    Monday, June 5, 2017 10:50 AM
  • User-1509636757 posted

    I am not sure for which Page number we are talking here. But, one thing is sure that you will require to implement it in PagerTemplate since default paging is not override with PagerTemplate. You can provide further details if you need any assistance.

    Monday, June 5, 2017 12:00 PM
  • User-614943948 posted

    The page number used in pagination as you can see in these 2 pictures. I am not using default paging, I am using custom paging, but I that shouldn't matter, but you can see the page numbers disappeared

    Monday, June 5, 2017 12:30 PM
  • User-1509636757 posted

    Since you are implementing Custom Paging with PagerTemplate; I think you will require to implement these pages numbers as well. I would be using Repeater control inside PagerTemplate and decide the numbers to be displayed (for example if total number of records are 55 and currently page size if 5 then I would do if (55/5) < 10 then use that number as max number else use 10 as max number; and bind a repeater with 1 to 10 (or the max number) numbers wrapped each number with a link button (again you will be using CommandName as "Page" and the particular page number as CommandArgument of the LinkButtons).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 5, 2017 5:29 PM
  • User-614943948 posted

    Brother thank you for all the help that you have provided. I will open a new thread for implementing these page numbers using a repeater control

    Tuesday, June 6, 2017 6:07 AM