Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2004-09-30
7
Medium Priority
?
12,431 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
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…

972 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