Solved

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

Posted on 2004-09-30
7
12,354 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

776 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