software
software

Reputation: 728

How to sort a value alphabeticaly in a dropdownlist? vb.net

I am trying to sort values in a dropdown , here is my code

   For Each Keystring as Long in HashValue.Keys 
      Dim LItem As New ListItem
      LItem.Text = cw.Name.ToString()
      LItem.Value = Keystring.ToString
      ddRole.Items.Add(LItem)
   Next

I tried LItem.Sort. but Sort was not defined property.

let me know the best way to sort values. thanks

Upvotes: 2

Views: 11071

Answers (3)

Eric Robinson
Eric Robinson

Reputation: 2095

the quick way is to put your ListItem into a List. Then sort that list using the default List .sort() method. Then bind it to your dropdown.

dim ddList as List(Of ListItem)
For Each Keystring as Long in HashValue.Keys 
    Dim LItem As New ListItem
    LItem.Text = cw.Name.ToString()
    LItem.Value = Keystring.ToString
    ddList.add(LItem)
Next

ddList.Sort()
ddRole.DataSource = ddList
ddRole.DataBind()

Upvotes: 1

Tomq
Tomq

Reputation: 1125

Try with lambda:

Items2Sort.Sort(function(x1,x2) x1.CompareTo(x2))

Of course if item is a string.

Upvotes: 1

pingoo
pingoo

Reputation: 2064

Have you tried just using OrderBy?

 For Each Keystring as Long in HashValue.Keys.OrderBy(Function(key) key) 
      Dim LItem As New ListItem
      LItem.Text = cw.Name.ToString()
      LItem.Value = Keystring.ToString
      ddRole.Items.Add(LItem)
 Next

Upvotes: 2

Related Questions