ASP.NET DropDownList with Custom Paging

Posted by: Malcolm Sheridan , on 6/28/2009, in Category ASP.NET
Views: 52981
Abstract: The following article demonstrates how to use a DropDownList control and page through it as if it were a GridView control.
ASP.NET DropDownList with Custom Paging
 
Let me start this article off by saying this is something I thought would be interesting to try as an exercise, but it might not fit into a real world scenario. All I wanted to achieve with this is if you can think of something cool to do in ASP.NET, try it! I was thinking about websites that have drop down lists that contain hundreds of items. I thought it would be nice to be able to page through the DropDownList items like you can do with a GridView. Well I came up with a solution!
For this example I’ll be connecting to the Northwind database. If you don’t have a copy of it, you can go here to download it.
Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.
 
New_Project
 
Open the page and drag a DropDownList control onto the page. Rename this control to cboNames:
 
<asp:DropDownList ID="cboNames" runat="server" AutoPostBack="True"
        OnSelectedIndexChanged="cboNames_SelectedIndexChanged">
    </asp:DropDownList> 
 
I’ve set AutoPostBack to true because I want to be able to page through the data. This example will use LINQ to SQL as the data access layer. Add a new LINQ to SQL Classes file to the project:
 
Add_NewWebApplication
 
Open the LINQ to SQL file in the designer and drag the Customers table onto the designer:
 
Linq_To_SQL
 
So now we have our code that connects to the database, let’s add the code to page through the data. For this to work I’ll be making use of the IQueryable Skip and Take methods. They take an integer value so it knows where to start and how many records to return from the query. Because these values will need to be saved during a postback, I’ll add them as properties that save the value to the ViewState:
 
C#
 
private int Take
{
      get
      {
            return (int)ViewState["Take"];
      }
      set
      {
            ViewState["Take"] = value;
      }
}
 
private int Skip
{
      get
      {
            return (int)ViewState["Skip"];
      }
      set
      {
            ViewState["Skip"] = value;
      }
}
 
VB.NET
 
Private Property Take() As Integer
      Get
             Return CInt(Fix(ViewState("Take")))
      End Get
        Set(ByVal value As Integer)
             ViewState("Take") = value
       End Set
End Property
 
Private Property Skip() As Integer
      Get
             Return CInt(Fix(ViewState("Skip")))
      End Get
       Set(ByVal value As Integer)
             ViewState("Skip") = value
       End Set
End Property
 
 
Now it’s time for the rest of the code. The bulk of the work is handled by the FetchData method:
 
C#
 
private void FetchData()
{
      using (NorthwindDataContext dc = new NorthwindDataContext())
      {
            cboNames.Items.Clear();               
            if (Skip > 0)
            {                   
            cboNames.Items.Add(new ListItem("<< Pre 10 Rows...", "Prev"));
             cboNames.AppendDataBoundItems = true;                   
            }
 
            var query = dc.Customers
                            .OrderBy(o => o.ContactName)
                            .Take(Take)
                            .Skip(Skip);
            cboNames.DataTextField = "ContactName";
            cboNames.DataSource = query.ToList();
            cboNames.DataBind();
 
            if (cboNames.Items.Count >= 10)
            {
              cboNames.Items.Add(new ListItem("Next 10 Rows >>", "Next"));   
            }
            cboNames.SelectedIndex = Skip > 0 ? 1 : 0;
      }
}
 
VB.NET
 
Private Sub FetchData()
      Using dc As New NorthwindDataContext()
             cboNames.Items.Clear()
                  If Skip > 0 Then
                        cboNames.Items.Add(New ListItem("<< Pre 10 Rows...", "Prev"))
                   cboNames.AppendDataBoundItems = True
                  End If
 
                  Dim query = dc.Customers.OrderBy(Function(o) o.ContactName).Take(Take).Skip(Skip)
                  cboNames.DataTextField = "ContactName"
                  cboNames.DataSource = query.ToList()
                  cboNames.DataBind()
 
                  If cboNames.Items.Count >= 10 Then
                   cboNames.Items.Add(New ListItem("Next 10 Rows >>", "Next"))
                  End If
                  cboNames.SelectedIndex = If(Skip > 0, 1, 0)
      End Using
End Sub
 
In the method above I first check to see if the Skip property is greater than zero. If it is then the user has moved from the first page and this is how they’ll navigate to the previous page. I am setting AppendDataBoundItems to true also. Without that once the data is bound to the control, all the existing values would be removed from the control. Next I am using LINQ to query the Customers object and return the rows between the Take and Skip values. This means at any time I will only return a subset of data making each call to the database as small as possible. Finally once the data has been bound to the control, I look at the number of items in the control. If it is greater or equal to 10 then I’ll display a Next 10 Rows >> link. The user can click on this to navigate to the next page.
 
Finally add the code to the SelectedIndexChanged event:
 
C#
 
protected void cboNames_SelectedIndexChanged(object sender, EventArgs e)
{
      if (cboNames.SelectedValue == "Next")
      {
            Take += 10;
            Skip += 10;
            FetchData();
      }
      else if (cboNames.SelectedValue == "Prev")
      {
            Take -= 10;
            Skip -= 10;
            FetchData();
      }  
}
 
VB.NET
 
Protected Sub cboNames_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
      If cboNames.SelectedValue = "Next" Then
             Take += 10
                  Skip += 10
                  FetchData()
       ElseIf cboNames.SelectedValue = "Prev" Then
             Take -= 10
                  Skip -= 10
                  FetchData()
       End If
End Sub
 
The Take and Skip values are incremented or decremented depending on whether or not the user selected Next or Previous. If you run the application you’ll see you have the option to page through the data like you can do in a GridView control:
 
Data
 
To make this code event better you could wrap up the DropDownList inside an UpdatePanel. That would make the transitions between postbacks slick. As I said this example was just an exercise of what you can do using ASP.NET. I enjoyed creating it and I hope you enjoyed it too.

The entire source code of this article can be  downloaded from here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Sascha on Wednesday, July 1, 2009 4:40 AM
Hi tehre, that's a great example for integrating paging into a ddl, however if i use that, i'm getting the following error:

System.NullReferenceException was unhandled by user code
  Message="Object reference not set to an instance of an object."
  Source="App_Web_admxy53c"
  StackTrace:
       at _Default.get_Take() in d:\Websites\PagingDropDownList\Default.aspx.cs:line 14
       at _Default.cboNames_SelectedIndexChanged(Object sender, EventArgs e) in d:\Websites\PagingDropDownList\Default.aspx.cs:line 81
       at System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e)
       at System.Web.UI.WebControls.DropDownList.RaisePostDataChangedEvent()
       at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent()
       at System.Web.UI.Page.RaiseChangedEvents()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  
This happen's when the method Take += 10; is beeing called, inside the getter property 'private int Take'.

Any help is appreciated.
Krgds
Sascha
Comment posted by Malcolm Sheridan on Friday, July 3, 2009 12:04 AM
@Sascha
Are you using the code available with this example?
Comment posted by Web Design Company on Tuesday, June 15, 2010 4:04 AM
Thanks. Really nice stuff!
Comment posted by online degree on Tuesday, July 6, 2010 3:14 AM
Excellent and a very simplistic and to the point. Wish I had developers like you around. Not only the drop down list but touching upon the delegate stuff was excellent.
Comment posted by conveyor rollers on Thursday, September 30, 2010 9:42 PM
Nice post.
Comment posted by Susancai on Friday, October 22, 2010 3:38 AM
I like this post
Comment posted by mathew on Thursday, January 20, 2011 10:43 PM
It looks like you've put a lot of effort into your article & the human race need a lot more of these on the Internet these days. I do not real have a large deal to say in retort, I just wanted to comment to tell well done. great post. i never thought of that.
Comment posted by jamiehout on Monday, February 14, 2011 1:46 AM

Spot on with this write-up, I actually think this web site needs way more consideration. I’ll probably be once more to learn much more, thanks for that info.
Comment posted by Web Design Company on Thursday, February 24, 2011 5:37 AM
really interesting stuff, thanks for such a great stuff
Comment posted by john mogh on Thursday, February 24, 2011 5:39 AM
its a awesome stuff thanks for sharing with us <a href="http://www.redchillimedia.com/web-design"/">web design company
</a>
Comment posted by Designer Jeans on Wednesday, March 9, 2011 3:31 AM
Good work,hope your blog be better!I just want to make a blog like this!

http://www.tallcouture.com/Shop-By-Category-Tall-Fashion/Denim
Comment posted by sudheer on Monday, March 28, 2011 11:54 PM
I am unable to implement the same using AJAX COMBOBOX, I get an error "cboNames.DataBind();" stating as Selected Value is out of range as it is not specified in the list....??  it works fine with regular dropdownlist but not working when I use the ASP.NET AJAX COBOBOX.
Comment posted by Essay Editing Service on Friday, August 26, 2011 5:38 AM
lot of good information, I come here all the time and am very happy with your updates, Thank you!
Comment posted by eyewear on Monday, September 12, 2011 3:41 AM
i just wanted to tell well done! <a href="http://eyewearconnection.com/gucci-lbc-99.html">gucci sunglasses</a>
Comment posted by freight company on Saturday, November 12, 2011 8:34 AM
Thanks for the post. I always enjoy reading your blog.    

Keep'em coming more frequently.

Best!
<a href="http://www.freightnshipping.com">freight company</a>  
Comment posted by Pulse Oximeter on Sunday, July 15, 2012 2:25 AM
That is very fascinating, You are an excessively skilled blogger
Comment posted by Shashikant on Thursday, August 1, 2013 7:01 AM
Problem is Dropdown does get populated when I used this code.

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook