Solved

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

Posted on 2004-09-30
7
12,359 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…

821 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