Solved

How to sort a listbox once the item was added to the list

Posted on 2004-09-30
7
12,385 Views
Last Modified: 2011-08-18
Hi,

How to sort a listbox once the item is added to the list.  If a new item is added it's added to the buttom of the list.  What is the techic to sort the list? Thank you
0
Comment
Question by:Edward Bekerman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 33

Expert Comment

by:raterus
ID: 12191694
Well there isn't any built-in functionality to do this.  The easiest way I can think of is go back to the datasource and rebind the sorted results with the new value added.  Or if your datasource was originally a DataTable, this is a snap if you add the new item, then manipulate a DataView to show you the sorted results.  If you don't want to do that, I guess you could probably do a little bubble sort on the listbox items.

--Michael
0
 
LVL 10

Expert Comment

by:jnhorst
ID: 12192465
The ListBox's Items collection has an Insert() method that takes the index at which you want to insert an item and either a ListItem object or a string object.  If you want to add an item that appears at the top of the list, just do this:

listbox.Items.Insert(0, "Select an Option")

Or you can do this:

Dim li As New ListItem("X", "Select and Option")
listbox.Items.Insert(0, li)

Of course, you could insert the item at any valid index.  If you have 10 items, you would not use index 15, of course (I have not tried that, so I do not know if it would throw an exception or just stick the item at the bottom of the list).

John
0
 
LVL 10

Expert Comment

by:jnhorst
ID: 12192503
As for sorting, here is how I handle all lists:

I have a table in the database called Lists.  It has these fields: ListName, ValueMember, DisplayMember, SortOrder.  Let's say I want a list of delivery methods including UPS, FexEx, and US Mail, in that order.  I would have three entries, each with the ListName column having "Delivery Methods", and the SortOrder field specifying how they should appear sort-wise.

I have a dataset with the Lists table as a DataTable.  But when I want to use a list, I add a DataView to the page and specify its table as the Lists table, the RowFilter="ListName = 'Delivery Methods'" and SortOrder in the Sort property.  I then bind the list to the DataView rather than the DataTable.  This sorts the list exactly as I want it.

John
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 15

Expert Comment

by:praneetha
ID: 12193194
ArrayList al=new ArrayList();
                  foreach(ListItem li in this.ListBox1.Items)
                  {
                        al.Add(li.Text);
                  }
                  
                  al.Sort();
                  this.ListBox1.DataSource=al;
                  this.DataBind();
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12193414
0
 
LVL 24

Accepted Solution

by:
Justin_W earned 500 total points
ID: 12204356
Here is some code to help with sorting DropDownList items:

You would use something like this:
            If (bSortByItemText) Then
                SortItems(myDropDownList, New ListItemTextComparer(bSortCaseSensitive))
            Else
                SortItems(myDropDownList, New ListItemValueComparer(bSortCaseSensitive))
            End If

with these utility methods:

#Region " ListItem Utility Methods "

        ''' <summary>
        ''' Creates and returns an array that contains all of the
        ''' <see cref="T:System.Web.UI.WebControls.ListItem" />s within a
        ''' <see cref="T:System.Web.UI.WebControls.ListItemCollection" />.
        ''' </summary>
        Public Shared Function ToArray(ByVal items As ListItemCollection) As ListItem()
            If (IsNothing(items)) Then
                Throw New System.ArgumentNullException("items")
            End If

            'Copy the items to an array
            Dim itemsArray() As ListItem
            itemsArray = CType(System.Array.CreateInstance(GetType(ListItem), items.Count), ListItem())
            items.CopyTo(itemsArray, 0)
            Return itemsArray
        End Function

#Region " Methods for sorting ListItems "

            ''' <summary>
            ''' Sorts a <see cref="T:System.Web.UI.WebControls.DropDownList" />'s
            ''' <see cref="T:System.Web.UI.WebControls.ListItem" />s.
            ''' </summary>
        Public Shared Sub SortItems( _
            ByRef dropdown As System.Web.UI.WebControls.DropDownList, _
            ByVal comparer As IComparer _
        )
            If (IsNothing(dropdown)) Then
                Throw New System.ArgumentNullException("dropdown")
            End If
            DropDownList.SortItems(dropdown, 0, dropdown.Items.Count, comparer)
        End Sub

        ''' <summary>
        ''' Sorts a <see cref="T:System.Web.UI.WebControls.DropDownList" />'s
        ''' <see cref="T:System.Web.UI.WebControls.ListItem" />s.
        ''' </summary>
        Public Shared Sub SortItems( _
            ByRef dropdown As System.Web.UI.WebControls.DropDownList, _
            ByVal index As Int32, _
            ByVal length As Int32, _
            ByVal comparer As IComparer _
        )
            If (IsNothing(dropdown)) Then
                Throw New System.ArgumentNullException("dropdown")
            ElseIf (IsNothing(comparer)) Then
                Throw New System.ArgumentNullException("comparer")
            End If

            If (dropdown.Items.Count < 1) Then
                Return 'Nothing to sort
            End If

            'Copy the DropDown's items to an array
            Dim items() As ListItem = ToArray(dropdown.Items)

            'Sort the array
            DropDownList.SortItems(items, index, length, comparer)

            'Replace the DropDown's items with the array elements
            dropdown.Items.Clear()
            dropdown.Items.AddRange(items)
        End Sub

        ''' <summary>
        ''' Sorts an array of <see cref="T:System.Web.UI.WebControls.ListItem" />s.
        ''' </summary>
        Public Shared Sub SortItems( _
            ByRef items() As ListItem, _
            ByVal index As Int32, _
            ByVal length As Int32, _
            ByVal comparer As IComparer _
        )
            If (IsNothing(items)) Then
                Throw New System.ArgumentNullException("items")
            ElseIf (IsNothing(comparer)) Then
                Throw New System.ArgumentNullException("comparer")
            End If

            If (items.Length < 1) Then
                Return 'Nothing to sort
            End If

            'Sort the array
            System.Array.Sort(items, index, length, comparer)
        End Sub

#End Region

#Region " IComparer Classes for sorting ListItems "

        ''' <summary>
        ''' Compares or sorts <see cref="T:System.Web.UI.WebControls.ListItem" /> instances by their
        ''' <see cref="P:System.Web.UI.WebControls.ListItem.Text" />s.
        ''' </summary>
        Public Class ListItemTextComparer
            Implements IComparer

            Private _IsCaseSensitive As Boolean = True

            Public Property IsCaseSensitive() As Boolean
                Get
                    Return Me._IsCaseSensitive
                End Get
                Set(ByVal value As Boolean)
                    Me._IsCaseSensitive = value
                End Set
            End Property

            Public Sub New(ByVal bIsCaseSensitive As Boolean)
                Me.IsCaseSensitive = bIsCaseSensitive
            End Sub

            Public Function Compare(ByVal x As Object, ByVal y As Object) _
                    As Integer Implements IComparer.Compare
                If (IsNothing(x) AndAlso IsNothing(y)) Then
                    Return 0
                ElseIf (IsNothing(x)) Then
                    Return -1
                ElseIf (IsNothing(y)) Then
                    Return 1
                Else
                    Dim listItem1 As ListItem = CType(x, ListItem)
                    Dim listItem2 As ListItem = CType(y, ListItem)
                    Return String.Compare(listItem1.Text, listItem2.Text, Me.IsCaseSensitive)
                End If
            End Function

        End Class

        ''' <summary>
        ''' Compares or sorts <see cref="T:System.Web.UI.WebControls.ListItem" /> instances by their
        ''' <see cref="P:System.Web.UI.WebControls.ListItem.Value" />s.
        ''' </summary>
        Public Class ListItemValueComparer
            Implements IComparer

            Private _IsCaseSensitive As Boolean = True

            Public Property IsCaseSensitive() As Boolean
                Get
                    Return Me._IsCaseSensitive
                End Get
                Set(ByVal value As Boolean)
                    Me._IsCaseSensitive = value
                End Set
            End Property

            Public Sub New(ByVal bIsCaseSensitive As Boolean)
                Me.IsCaseSensitive = bIsCaseSensitive
            End Sub

            Public Function Compare(ByVal x As Object, ByVal y As Object) _
                    As Integer Implements IComparer.Compare
                If (IsNothing(x) AndAlso IsNothing(y)) Then
                    Return 0
                ElseIf (IsNothing(x)) Then
                    Return -1
                ElseIf (IsNothing(y)) Then
                    Return 1
                Else
                    Dim listItem1 As ListItem = CType(x, ListItem)
                    Dim listItem2 As ListItem = CType(y, ListItem)
                    Return String.Compare(listItem1.Value, listItem2.Value, Me.IsCaseSensitive)
                End If
            End Function

        End Class

#End Region

#End Region
0
 

Author Comment

by:Edward Bekerman
ID: 12374645
Thanks a lot.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question