Extending GridView Control: Using a DropDownList Pager

Introduction

There are lots of ways of creating custom paging in GridView. Most of the ones I've seen implement in PagerTemplate. This is tedious if you have several pages in your application and/or several applications that use GridView and you want them to have a similar appearance. In this article, I will share what I came up with: an inherited GridView control with DropDownList and Label in the Pager section. The DropDownList is your page number and the Label displays what record number you are currently in.

Using the code

To start with, let us create a Website Project and a Class Library Project. Name the Class Library Project, say, EuoControl. Add a Web Custom Control and let us name it GridEuo. Instead of inheriting from WebControl, inherit it from GridView.

Screenshot - GridViewDropDownPager1.png

Our main objective here is to render the Pager with the DropDownList and Label controls. So, we need to override InitializePager in our base control GridView.

Collapse
protected override void InitializePager(GridViewRow row, 
    int columnSpan, PagedDataSource pagedDataSource)
{
    // create our DropDownList control
    DropDownList ddl = new DropDownList();
    // populate it with the number of Pages of our GridView
    for (int i = 0; i < PageCount; i++)
    {
        ddl.Items.Add(new ListItem(Convert.ToString(i + 1), i.ToString()));
    }
    ddl.AutoPostBack = true;
    // assign an Event Handler when its Selected Index Changed
    ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
    // synchronize its selected index to GridView's current PageIndex
    ddl.SelectedIndex = PageIndex;

    // create a Table that will replace entirely our GridView's Pager section
    Table tbl = new Table();
    tbl.BorderWidth = 0;
    tbl.Width = Unit.Percentage(100);
    // add one TableRow to our Table
    tbl.Rows.Add(new TableRow());

    // add our first TableCell which will contain the DropDownList 
    TableCell cell_1 = new TableCell();

    // we just add a Label with 'Page ' Text
    cell_1.Controls.Add(PageOf());

    // our DropDownList control here.
    cell_1.Controls.Add(ddl);

    // and our Total number of Pages
    cell_1.Controls.Add(PageTotal());

    // the 2nd TableCell will display the Record number you are currently in.
    TableCell cell_2 = new TableCell();
    cell_2.Controls.Add(PageInfo(pagedDataSource.DataSourceCount));

    // add now the 2 cell to our created row
    tbl.Rows[0].Cells.Add(cell_1);
    tbl.Rows[0].Cells.Add(cell_2);
    tbl.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Left;
    tbl.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Right;

    // in Pager's Row of our GridView add a TableCell 
    row.Controls.AddAt(0, new TableCell());
    // sets it span to GridView's number of columns
    row.Cells[0].ColumnSpan = Columns.Count;
    // finally add our created Table
    row.Cells[0].Controls.AddAt(0, tbl);
}

protected virtual void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
    // on our DropDownList SelectedIndexChanged event
    // call the GridView's OnPageIndexChanging method 
    // to raised the PageIndexChanging event.
    // pass the DropDownList SelectedIndex as its argument.
    OnPageIndexChanging(new GridViewPageEventArgs(
        ((DropDownList)sender).SelectedIndex));
}

protected virtual Label PageOf()
{ 
    // it is just a label
    Label lbl = new Label();
    lbl.Text = "Page ";
    return lbl;
}

protected virtual Label PageTotal()
{
    // a label of GridView's Page Count
    Label lbl = new Label();
    lbl.Text = string.Format(" of {0}", PageCount);
    return lbl;
}

protected virtual Label PageInfo(int rowCount)
{
    // create a label that will display the current Record you're in
    Label label = new Label();
    int currentPageFirstRow = ((PageIndex * PageSize) + 1);
    int currentPageLastRow = 0;
    int lastPageRemainder = rowCount % PageSize;
    currentPageLastRow = (PageCount == PageIndex + 1) ? (
        currentPageFirstRow + lastPageRemainder - 1) : (
        currentPageFirstRow + PageSize - 1);
    label.Text = String.Format(
        "Record {0} to {1} of {2}", currentPageFirstRow, 
        currentPageLastRow, rowCount);
    return label;
}

One way or another, you may want to opt out the DropDownList Pager. So, let us add a Property that will enable you to choose what PagerType to use.

[Category("Paging")]
[DefaultValue("1")]        
public ThisPagerType PagerType
{
    get
    {
        return (ViewState["PagerType"] != null ? (
           ThisPagerType)ViewState["PagerType"] : ThisPagerType.DropDownList);
    }
    set
    {
        ViewState["PagerType"] = value;
    }
}

public enum ThisPagerType
{
    Regular = 0,
    DropDownList = 1
}

Let us now modify the InitializePager method.

if (PagerType != ThisPagerType.DropDownList)
{
    // if PagerType is not DropDownList
    // render the regular GridView Pager
        base.InitializePager(row, columnSpan, pagedDataSource);
}
else
{
    // our Pager with DropDownList control
    // .
    // .
    // .
}

So, that is it! You may compile and distribute the DLL, but first, let us take it into action. In the Website Project we created earlier, add a reference to our Control Library.

Screenshot - GridViewDropDownPager2.png

Drag two (2) GridEuo controls onto the Webform. Set both controls' AllowPaging Property to True. In the 1st GridEuo, set AutoGenerateColumns to False and add DataBound columns. Set the PagerType Property of the 2nd GridEuo to Regular.

Screenshot - GridViewDropDownPager4.png

Add this in the code-behind:

Collapse
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}
private void BindGrid()
{
    // i am using 'Products' table of the 'Northwind' database
    SqlConnection cn = new SqlConnection(
        "server=(local);database=northwind;uid=sa;pwd=;");
    string q = "select productname, quantityperunit from products";
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(q, cn);
    cn.Open();
    da.Fill(ds);

    // the 1st GridEuo
    GridEuo1.DataSource = ds;
    GridEuo1.DataBind();

    // the 2nd GridEuo
    GridEuo2.DataSource = ds;
    GridEuo2.DataBind();

    cn.Close();        
}    
protected void GridEuo1_PageIndexChanging(
    object sender, GridViewPageEventArgs e)
{
    GridEuo1.PageIndex = e.NewPageIndex;
    BindGrid();
}
protected void GridEuo2_PageIndexChanging(
    object sender, GridViewPageEventArgs e)
{
    GridEuo2.PageIndex = e.NewPageIndex;
    BindGrid();
}

That's all; run your project. You should see something like this:

Screenshot - GridViewDropDownPager3.png

http://www.codeproject.com/cs/miscctrl/ExtendingGridViewControl.asp

posted on 2007-07-11 09:46  石川  阅读(371)  评论(0编辑  收藏  举报