Solved

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

Posted on 2004-09-30
7
12,333 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 15

Expert Comment

by:praneetha
Comment Utility
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
Comment Utility
0
 
LVL 24

Accepted Solution

by:
Justin_W earned 500 total points
Comment Utility
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
Comment Utility
Thanks a lot.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now