Monday, July 4, 2011

ASP.NET - Paging in DataList control and binding generic List to DataList control in horizontal orientation


Paging in DataList control and binding generic List to DataList control in horizontal orientation.
June was very heavy because of work. I could not get time to write a blog post. July looks better as I am free. Client rejected all the efforts I put in the month of June and cancelled the project. I hate clients..!!
Hmmm…Anyways, during that time in June, I had implemented many things which look simple but hard to find on Google. Here is the one. Implement Paging in DataList control. I was so much used to GridView control that I never devoted time to look at DataList control. And when I had to work with DataList, I was stuck with basic functionality of paging even.


Alright here we go –
 
Problem Statement – How to bind a data list control with generic List having user defined class collection in it? How to implement paging in data list control? Also I want to show the records in horizontal orientation as shown below –


My user defined class is Product. My products will be Penguins as shown above. Strange huh?..Anyways strange things happen in Software industry only. J
 So I want to bind List<Product> to data list control. For this I will use PagedDataSource class.
Product class is as follows –
[Serializable]
    public class Product


    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }       
        public string Url { get; set; }       
    }

My aspx side is as follows –
<div id="Div2">
            <table>
                <tr>
                    <td style="vertical-align: middle;">
                        <asp:Button ID="btnPrevious" runat="server" Text="<<"                                                                                    OnClick="btnPrevious_Click" />
                    </td>
                    <td>
                        <asp:DataList ID="dlServicesSubStores" runat="server"   RepeatDirection="Horizontal">
                            <ItemTemplate>
                                <li><span class="border3">
                                    <asp:ImageButton ID="imgbtnServicesSubStore" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "Url")%>'
                                        DescriptionUrl="http://www.google.com/" runat="server" Width="135" Height="107" />
                                </span>
                                    <h5>
                                        <asp:HyperLink ID="hlServicesSubStoreTitle" runat="server" NavigateUrl="http://www.google.com/">'<%#DataBinder.Eval(Container.DataItem, "Title")%>'</asp:HyperLink>
                                    </h5>
                                </li>
                            </ItemTemplate>
                        </asp:DataList>
                    </td>
                    <td style="vertical-align: middle;">
                        <asp:Button ID="btnNext" runat="server" Text=">>" OnClick="btnNext_Click" />
                    </td>
                </tr>
            </table>
        </div>

The text marked with Pink background actually refers to Product class Properties. Text in Eval method must be same as Property name in Product. This applies to your class also.

Following code has to be written in Code behind –
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Product> products = this.CreateDummyProductList();

                //add sub stores of the current service to viewstate
                ViewState["Products"] = products;

                this.PopulateProducts(products);
            }
        }

 /// <summary>
        /// set or get the Current Page Number
        /// </summary>
        public int CurrentPage
        {
            get
            {
                //get current page number
                object obj = this.ViewState["_CurrentPage"];

                if (obj == null)
                {
                    return 0;
                }
                else
                {
                    return (int)obj;
                }
            }
            set
            {
                //set in viewstate the current page number
                this.ViewState["_CurrentPage"] = value;
            }
        }

protected void btnNext_Click(object sender, EventArgs e)
        {
            //go to next page
            CurrentPage += 1;
            this.PopulateProducts((List<Product>)ViewState["Products"]);
        }

protected void btnPrevious_Click(object sender, EventArgs e)
        {
            //back to previous page
            CurrentPage -= 1;
            this.PopulateProducts((List<Product>)ViewState["Products"]);
        }

private void PopulateProducts(List<Product> products)
        {
            //create new instance of PagedDataSource
            PagedDataSource objPds = new PagedDataSource();

            //set number of pages that will appear in datalist
            objPds.PageSize = 4;

            objPds.DataSource = products;
            objPds.AllowPaging = true;
            int count = objPds.PageCount;


            objPds.CurrentPageIndex = CurrentPage;
            if (objPds.Count > 0)
            {
                //dispaly controls if there are pages
                btnPrevious.Visible = true;
                btnNext.Visible = true;              

            }
            else
            {
                //disable controls if there are no pages
                btnPrevious.Visible = false;
                btnNext.Visible = false;               
            }

            btnPrevious.Enabled = !objPds.IsFirstPage;
            btnNext.Enabled = !objPds.IsLastPage;
           
            //bind datalist to paged data source
            dlServicesSubStores.DataSource = objPds;
            dlServicesSubStores.DataBind();
        }

private List<Product> CreateDummyProductList()
        {
            //creating List for the data
            List<Product> products = new List<Product>();

            for (int count = 0; count < 12; count++)
            {
                Product product = new Product();
                product.Url = "img/Penguins.jpg";
                product.Title = "Penguins are good " + count.ToString();

                products.Add(product);
            }
            return products;
        }

That’s it. You are done with paging in Data List control.
Cheers…
Happy Coding!!


No comments:

Post a Comment