Archive

Posts Tagged ‘Add dropdown list to pager’

Customizing Gridview pager

As a computer programmer it is very important for all of us to present data  to end users in as efficient and uncomplicated way as possible. Gridview is one of the control that we use very often to present large amount of data in our applications. Since Framework 1.1 DataGrid and Gridview has built-in support for paging and whenever we have large data to deal with we activate pager support  so users would get better UI experience. Enable paging support for Gridview is a no-brainer but if you want to customize it then you need to write a bit of code. Below is an image of  a Gridview header with customized pager and that is what we will try to achieve today.

Gridview with customized Pager

As you see the Gridview header in above picture has a basic pager control and other than that it has Next and Last link buttons, Previous and First options will be available when we move to the pages above page number 10. We are also going to add a Dropdown list to our pager and use it for setting the page size of our grid view. With all these options we are also going to add couple of titles to our pager.

To start with paging we need  to set AllowPaging=”True” in our Gridview. With that we need to handle Gridview’s page index changing event and set the page index property, also don’t forget to re-bind the Gridview otherwise you will not get the correct data. Here is an example of how we do that:

 Page Index Changing Event Handler

Here is what we are going to get after enabling the basic pager for our grid view;

Basic Pager

Now if you see the above image it is the basic pager functionality. Now to enhance the functionality we are going to make some simple modifications. First of all we are going to change the mode property to “NumericFirstLast” as we need First and Last buttons with page numbers. Now if you browse the page you will see >> << symbols at start and end of the page numbers and if you click these symbols it will take you to the first and last age. Instead of these symbols we need Next and Last buttons and for that we are going to set the FirstPageText=”First” and LastPageText=”Last”. If you execute the code now you will see the First and Last links instead of  symbols. With first and last buttons we also need  “Next” and “Previous” options with page numbers and we can achieve it by following code:

  protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            Table pgTable = (Table)e.Row.Cells[0].Controls[0];
            TableRow pgRow = (TableRow)pgTable.Rows[0];
            int pgRowCellCount = pgRow.Cells.Count;
            PagerSettings PgSettings = ((GridView)sender).PagerSettings;
            if (PgSettings.Mode == PagerButtons.NumericFirstLast)
            {
                int prevButton = 1;
                int nextButton = pgRowCellCount – 2;
                if (prevButton < pgRowCellCount)
                {
                    LinkButton btnPrevious = pgRow.Cells[prevButton].Controls[0] as LinkButton ;
                    if (btnPrevious != null && btnPrevious.Text.IndexOf(“…”) != -1)
                    {
                        btnPrevious.Text = PgSettings.PreviousPageText;
                        btnPrevious.CommandName = “Page”;
                        btnPrevious.CommandArgument = “Prev”;
                    }
                }
                if (nextButton > 0 && nextButton < pgRowCellCount )
                {
                    LinkButton btnNext = pgRow.Cells[nextButton].Controls[0] as LinkButton ;
                  
                    if (btnNext != null && btnNext.Text.IndexOf(“…”) != -1)
                    {
                        btnNext.Text = PgSettings.NextPageText;
                        btnNext.CommandName = “Page”;
                        btnNext.CommandArgument = “Next”;
                    }
               
                }

            } 
        }

}

 When you set the pager mode to “NumericFirstLast” it shows “…” links in pager control at start and end of the page numbers. Now what we will do here is get the index of “…” links on the pager row and replace it with Next and Previous buttons. If you run the code now you will see the Next and Previous buttons in the pager.

Pager with Previous Button

Pager with Next Button

Ok so we have done some cool customization to our pager and what we will do now is add a caption “Page:”  before page numbers and to do this we will add “RowCreated” event handler for our grid view and add a literal control to the pager row. 

 protected void grdData_RowCreated(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.Pager)
        {
            Table pgTable = e.Row.Cells[0].Controls[0] as Table;
            TableCell  tc = new TableCell();
            tc.Controls.Add(new LiteralControl(“Page: “));
            pgTable.Rows[0].Cells.AddAt(0, tc);
        }

}

We are almost done here and at the end we will add a Dropdown list to our pager which will tell the grid view how many rows to display at a time. To do this we will create a Dropdown control on runtime and fill it with required values. We will also add an event handler to capture the “SelectedIndexChanged” event and grab the selected values in Dropdown list.

Add this code to row_created event of grid view

 DropDownList ddlPageSize = new DropDownList();
            ddlPageSize.Items.Add(“5”);
            ddlPageSize.Items.Add(“10”);
            ddlPageSize.Items.Add(“15”);
            ddlPageSize.AutoPostBack = true;
           
            ListItem li = ddlPageSize.Items.FindByText(grdData.PageSize.ToString());
            if (li != null)
                ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(li);
            ddlPageSize.SelectedIndexChanged += new EventHandler(ddlPageSize_SelectedIndexChanged);

Also add the event handler for drop down

 protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {

        grdData.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
        BindData();
    }

And now when you run the code you will see the pager control which is exactly the same that you have seen at start of this post. Here is the complete code:

Client Side Code:

       GridView ID=”grdData” Width=”50%” runat=”server” AutoGenerateColumns=”False”
            AllowPaging=”True” PageSize=”5″ OnPageIndexChanging=”grdData_PageIndexChanging” OnRowDataBound=”grdData_RowDataBound”
            OnRowCreated=”grdData_RowCreated” CellPadding=”4″ ForeColor=”#333333″ GridLines=”None” AllowSorting=”true” >
            <PagerSettings Mode=”NumericFirstLast”  FirstPageText=”First” LastPageText=”Last” NextPageText=”Next” PreviousPageText=”Prev”
                 Position=”TopAndBottom”  />
            <RowStyle BackColor=”#F7F6F3″  ForeColor=”#333333″ />
            <Columns>          
         BoundField DataField=”FirstName” HeaderText=”First Name” SortExpression=”FirstName” />
        BoundField DataField=”LastName” HeaderText=”Last Name” SortExpression=”LastName” />
        BoundField DataField=”Email” HeaderText=”Email Address” SortExpression=”Email” />        
            </Columns>
            <FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
            <PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
            <SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
            <HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
            <EditRowStyle BackColor=”#999999″ />
            <AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
        GridView>

Server side code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.BindData();
       
        }
    }

    protected void BindData()
    {
        Data objData = new Data();
        grdData.DataSource= objData.GetUserList();
        grdData.DataBind();
    }
    protected void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdData.PageIndex = e.NewPageIndex;
        BindData();
    }
    protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            Table pagerTable = (Table)e.Row.Cells[0].Controls[0];
            TableRow pagerRow = pagerTable.Rows[0];
          
            PagerSettings pagerSettings = ((GridView)sender).PagerSettings;
            int cellsCount = pagerRow.Cells.Count;
            if (pagerSettings.Mode == PagerButtons.Numeric
                             || pagerSettings.Mode == PagerButtons.NumericFirstLast)
            {

                int prevButtonIndex = pagerSettings.Mode == PagerButtons.Numeric ? 0 : 2;
                int nextButtonIndex = pagerSettings.Mode == PagerButtons.Numeric ? cellsCount – 1 : cellsCount – 3;
                if (prevButtonIndex < cellsCount)
                {
                   
                    LinkButton btnPrev = pagerRow.Cells[prevButtonIndex].Controls[0] as LinkButton;
                    if (btnPrev != null && btnPrev.Text.IndexOf(“…”) != -1)
                    {
                        btnPrev.Text = pagerSettings.PreviousPageText;
                        btnPrev.CommandName = “Page”;
                        btnPrev.CommandArgument = “Prev”;
                    }
                }
                if (nextButtonIndex > 0 && nextButtonIndex < cellsCount)
                {
                 
                    LinkButton btnNext = pagerRow.Cells[nextButtonIndex].Controls[0] as LinkButton;
                    if (btnNext != null && btnNext.Text.IndexOf(“…”) != -1)
                    {
                        btnNext.Text = pagerSettings.NextPageText;
                        btnNext.CommandName = “Page”;
                        btnNext.CommandArgument = “Next”;
                    }
                }
            }
        }

    }
    protected void grdData_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
            TableCell tc = new TableCell();
            tc.Controls.Add(new LiteralControl(“Page: “));
            pagerTable.Rows[0].Cells.AddAt(0, tc);

            DropDownList ddlPageSize = new DropDownList();
            ddlPageSize.Items.Add(“5”);
            ddlPageSize.Items.Add(“10”);
            ddlPageSize.Items.Add(“15”);
            ddlPageSize.AutoPostBack = true;
           
            ListItem li = ddlPageSize.Items.FindByText(grdData.PageSize.ToString());
            if (li != null)
                ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(li);
            ddlPageSize.SelectedIndexChanged += new EventHandler(ddlPageSize_SelectedIndexChanged);

            TableCell cell = new TableCell();
            cell.Style[“width”] = “100%”;
            cell.Style[“padding-left”] = “15px”;
            cell.Style[“text-align”] = “right”;
            cell.Controls.Add(new LiteralControl(“PageSize: “));
            cell.Controls.Add(ddlPageSize);
            pagerTable.Rows[0].Cells.Add(cell);
        }
    }
    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {

        grdData.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
        BindData();
    }

Enjoy coding.