CODEDIGEST
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Paging in ListView in ASP.Net 3.5  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Sponsors
InstallShield
 

Product Spotlight
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Paging in ListView in ASP.Net 3.5
Free Trial: InstallShield 2010 for Windows Installers Is InstallShield right for you? InstallShield handles your most complex installation requirements in minutes. Try it now.

By Satheesh babu
Posted On Jul 22,2008
Article Rating: (Login)
Average Rating: 5
No of Ratings: 1
No of Comments: 10
Category: ASP.Net 3.5
Print this article.

Subscribe to our feed!

Paging in ListView in ASP.Net 3.5


My previous article, ListView Control in ASP.Net 3.5, provides a good understanding on the ListView control with a sample databinding. Our next step in exploring the ListView control is to add the paging feature to it. Like GridView, Paging in ListView control is not an integral part of the control itself. It can be provided through a new control in ASP.Net 3.5 called DataPager control. The main advantage of providing this feature with a new control are, Paging can be separated from ListView Control and can be displayed at any part of the page.  We can attach the paging feature with the ListView control by placing the DataPager control in the LayoutTemplate of the ListView control which resembles GridView control.

InstallShield
In this article, we will implement paging feature with DataPager control in 3 different ways,

Ø       Paging in ListView through Datasource control databind.

Ø       Paging in ListView without using DataSource Controls.

Ø       Providing Custom interface for the Paging in ListView.

 

Paging in ListView through Datasource control databind

Before moving to paging implementation with DataPager we will bind the ListView by configuring a SqlDataSource control.

Configuring SqlDataSource Control

Drag a SqlDataSource control from the data tab of Visual Studio 2008. Configure it with the Database Server; I have used a database in App_Data folder.

Configuring ListView Control

Drag a ListView control from the data tab of Visual Studio 2008.  Click the Smart tag of ListView control and select the datasource control; Refer the below figure, SqlDataSource1 in our example.

ListView

 

Click “Configure ListView...” option as seen in the above figure to choose the display Layout for the ListView. Choose a display layout, I have selected “Flow” in our example, as seen in the below figure. Click Ok.

ListView with DataPager

You can check “Enable Paging” in the above figure, which will add a DataPager control in the LayoutTemplate of the ListView control but we will add the DataPager control explicitly in this article. Executing the page will display the records without paging. Now, we will provide paging feature through the DataPager control.

Configure Paging through DataPager

Drag a DataPager control from the data tab of Visual Studio 2008. Assign the PagedControlID property to the ListView control’s ID. Set PageSize property if required, default is 10. I have set as 2 in our example.

There are 2 default pager styles that can be set to a DataPager control, Next/Previous Pager and Numeric Pager. Without setting this there will be no pagination displayed for the ListView. To configure, Click the smart tag of DataPager control and choose the style as shown in the below figure,

ListView

Executing the page will give output with paging,

ListView

 

Configuring DataPager inside ListView

The above walkthrough placed the DataPager control outside the ListView control, in other words, the paging can be displayed at any part of the page. In this section, we will see how the DataPager can be a part of ListView control itself.

It can be done by placing the DataPager control inside the LayoutTemplate of the ListView. In this case, we neither need nor set the PagedControlID property because DataPager control itself will render accordingly when it is placed inside the ListView control.

<asp:ListView ID="ListView1" runat="server" DataKeyNames="EmpID"

        DataSourceID="SqlDataSource1">

       <LayoutTemplate>

        <asp:DataPager ID="dpListView" runat="server" PageSize="2">

        <Fields>

        <asp:NumericPagerField ButtonType="Button" NextPageText="more.." />

        </Fields>

        </asp:DataPager>

        <div ID="itemPlaceholderContainer" runat="server"

                style="font-family: Verdana, Arial, Helvetica, sans-serif;">

        <span ID="itemPlaceholder" runat="server" />

            </div>

            <div style="text-align: center;background-color: #CCCCCC;font-family: Verdana,      Arial, Helvetica, sans-serif;color: #000000;">

            </div>

        </LayoutTemplate>

       <ItemTemplate>

            <span style="background-color: #DCDCDC;color: #000000;">EmpID:

            <asp:Label ID="EmpIDLabel3" runat="server" Text='<%# Eval("EmpID") %>' />

            <br />

            EmpName:

            <asp:Label ID="EmpNameLabel1" runat="server" Text='<%# Eval("EmpName") %>' />

            <br />

            Department:

            <asp:Label ID="DepartmentLabel1" runat="server"

                Text='<%# Eval("Department") %>' />

            <br />

            Age:

            <asp:Label ID="AgeLabel1" runat="server" Text='<%# Eval("Age") %>' />

            <br />

            Address:

            <asp:Label ID="AddressLabel1" runat="server" Text='<%# Eval("Address") %>' />

            <br />

            <br />

            </span>

        </ItemTemplate>

</asp:ListView>

 

In the next section, we will provide paging to ListView control with DataPager without using DataSource controls.


Paging with DataPager without using DataSource Controls

1.      Drag a ListView control inside a webform as we did in previous section.

<asp:ListView ID="lvEmployee" runat="server">

        <LayoutTemplate>              

         <table ID="itemPlaceholderContainer" >          

           <tr runat="server" ID="itemPlaceholder">

           </tr>

        </table>

         </LayoutTemplate>

        <ItemTemplate>

              <tr>

                <td>

                  EmpID:  <asp:Label ID="EmpIDLabel" runat="server" Text='<%# Eval("EmpID") %>' />

                <br />

                   EmpName: <asp:Label ID="EmpNameLabel" runat="server"

                        Text='<%# Eval("EmpName") %>' />

               <br />

                    Department:<asp:Label ID="DepartmentLabel" runat="server"

                        Text='<%# Eval("Department") %>' />

               <br />

                  Age:  <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />

              <br />

                    Address:<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />

                </td>

            </tr>

       </ItemTemplate>

</asp:ListView>

 

2.      In the codebehind file, assign the DataTable or DataSet to the DataSource Property of the ListView control like we do for a GridView control.

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            lvEmployee.DataSource = GetEmployee("Select * from Employee");

            lvEmployee.DataBind();

        }

    }

    public DataTable GetEmployee(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dtEmp = new DataTable();

        ada.Fill(dtEmp);

        return dtEmp;

    }

3.      Drag a DataPager control from the Data tab of visual studio. When we execute the page, Paging will not work automatically; we need to bind the ListView to the datasource again in the PreRender event of DataPager.

<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee"

       PageSize="2" onprerender="DataPager1_PreRender">

<Fields>

 <asp:NextPreviousPagerField ButtonType="Button" />

 </Fields>

</asp:DataPager>

 

protected void DataPager1_PreRender(object sender, EventArgs e)

    {

        lvEmployee.DataSource = GetEmployee("Select * from Employee");

        lvEmployee.DataBind();

    }

Execute the page and you can see your ListView paging working perfectly.


Sponsors

Useful Books For Developers
ASP.NET 3.5 Application Architecture More books..

Similar Articles

Providing Custom interface for the Paging in ListView

The previous 2 sections of this article provided the paging interface as a Previous, Next button or a numeric pager. Sometimes, we may require a textbox or a dropdown where will select our page number and display the corresponding page in the ListView control. Refer the below figure to have more understanding,

ListView

 

This can be achieved by <asp:TemplatePagerField> of the DataPager.

First, we will implement the page selection via the DropDownList control.

Navigate to a page using DropDownList

<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee"

            PageSize="3" onprerender="DataPager1_PreRender">

            <Fields>

            <asp:NumericPagerField ButtonType="Link" ButtonCount="2"  />

               <asp:TemplatePagerField>

              <PagerTemplate>

              <asp:DropDownList ID="ddlPage" runat="server" AutoPostBack="true"                        OnSelectedIndexChanged="ddlPage_SelectedIndexChanged"></asp:DropDownList>       

</PagerTemplate>

             </asp:TemplatePagerField>

            </Fields>

</asp:DataPager>    

 

We can fill the dropdownlist with page numbers in the DataBound event of the ListView. In SelectedIndexChanged event of dropdownlist, we can bind the corresponding page using SetPageProperties method of DataPager.

 

   int CurrentPage = 0;

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            lvEmployee.DataSource = GetEmployee("Select * from Employee order by empid");

            lvEmployee.DataBind();

        }

    }

    public DataTable GetEmployee(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dtEmp = new DataTable();

        ada.Fill(dtEmp);

        return dtEmp;

    }

    protected void lvEmployee_DataBound(object sender, EventArgs e)

    {

        DropDownList ddl = DataPager1.Controls[1].FindControl("ddlPage") as DropDownList;                      

        int PageCount = (DataPager1.TotalRowCount / DataPager1.PageSize);

        if(PageCount*DataPager1.PageSize != DataPager1.TotalRowCount)

        {

              PageCount = PageCount + 1;

        }            

        for (int i = 0; i < PageCount; i++ )

        {

            ddl.Items.Add(new ListItem((i+1).ToString(),i.ToString()));

        }

        ddl.Items.FindByValue(CurrentPage.ToString()).Selected = true;

    }

    protected void ddlPage_SelectedIndexChanged(object sender, EventArgs e)

    {

        DropDownList ddl = sender as DropDownList;

        CurrentPage = int.Parse(ddl.SelectedValue);

        int PageSize = DataPager1.PageSize;

        DataPager1.SetPageProperties(CurrentPage * PageSize, PageSize, true);

    }

    protected void DataPager1_PreRender(object sender, EventArgs e)

    {

        lvEmployee.DataSource = GetEmployee("Select * from Employee order by empid");

        lvEmployee.DataBind();

    }

When we execute the page, we can navigate between the pages using the dropdownlist.

Navigate to a page using TextBox control

To navigate to a particular page using the textbox control we can use the below code. Since, we have seen how to use a control inside DataPager control we will put the textbox control outside the DataPager and bind the ListView.

 protected void btnGoPage_Click(object sender, EventArgs e)

{

        if(txtPage.Text != "")

        DataPager1.SetPageProperties( (int.Parse(txtPage.Text)-1) * DataPager1.PageSize, DataPager1.PageSize, true);

}

 

The above code will navigate to the page number entered in the TextBox control.

Download

Source code

 

Conclusion

We have learnt providing paging feature to the ListView control in 3 different scenarios. Most of the time, we will go for binding the ListView without using a DataSource controls which is because we will have our own layers of code in an enterprise project. We will see more ListView controls and its usages in my coming articles. Download the source attached with this article and see it in action.

Happy Coding!!!

You can contribute to CodeDigest.Com:
Donate to CodeDigest.com
Article Feedback
Title  
Submitted By  
Comment  
Enter the verification number
 
Comments
onprerender in listview or datapager??
I had this problem when i tried to call onprerender event for datapager.. it gave some exception saying that control collection cannot be changed during certain events.. but the same event worked when i called for listview.. so please check whether its the listview or datapager, where the event has to be called..
error
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

This is what happens when I try databind the pager during preRender?
Thank You
This article saved me a lot of time. Great explanation
Nice Article
Hi,
This is a nice article. This helped me lot as I am using ListView First Time.
Good Articles
Nice artcile. Good explenation on pagination for Listview.
Mr
Hi,

Very nice article.Was very helpful.

Thanks,
Thani
Bueatiful!!!
Excellent article! My co-workers and I are fairly new to the .NET world and we've been searching for a while on how to get the data pager to work even though it's a fairly simple thing. This is the first article I've found that tells you to rebind the pager on the PreRender event. Thank you very much! Very easy to follow.
Fantastic Article!
This is a great article! It described things in simple terms, was easy to follow, and gave step by step examples of different, real-world implementations. It's hard to find articles this clear and to the point. Thanks a million!
Problem Solved!
Great article! Just wanted to show my appreciation due to the time it has saved me faffing about with my DataSet :)
Great Article
Great Article. Got what i was looking for.