.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Collections >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Sort List box in ASP .Net using System.Collections.SortedList

Posted By:Prasanti Prusty       Posted Date: December 20, 2009    Points: 10    Category: Collections    URL: http://www.dotnetspark.com  
 

Sort List box in ASP .Net using  System.Collections.SortedList
SortedList :

SortedList Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.

Code Behind :

Partial Class SortListBox
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            If Not IsPostBack Then

                'Let List box Having the following Item.
                Dim strcountry() As String = {"Denmark", "China", "Italy", "Australia", "India", "Egypt", "Bhutan"}
                Dim strcountryID() As String = {"Den", "Chi", "Ita", "Aus", "Ind", "Egy", "Bhu"}

                'Populate the List Box
                For i As Int16 = 0 To strcountry.Length - 1

                    ListBox1.Items.Add(i)
                    ListBox1.Items(i).Text = strcountry(i)
                    ListBox1.Items(i).Value = strcountryID(i)
                Next

            End If

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    'Click on btnSort to Sort the ListBox.
    Protected Sub btnSort_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSort.Click
        Try

            'Use the object of SortedList to Sort the Items
            Dim objSortlst As New SortedList

            For i As Int16 = 0 To ListBox1.Items.Count - 1

                'objSortlst.Add(key,value) . It keeps value in sorted Order
                objSortlst.Add(ListBox1.Items(i).Text, ListBox1.Items(i).Value)
            Next

            'Now objSortlst is having data in Sorted order of Key
            ListBox1.DataSource = objSortlst
            ListBox1.DataTextField = "key"
            ListBox1.DataValueField = "value"
            ListBox1.DataBind()

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

End Class

 


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend