Reverse sorting an array.....Array.Reverse(strTheString)

jbl_ks

Member
Joined
Dec 16, 2010
Messages
24
Programming Experience
Beginner
I have tried the show the revelent code below.
I have the array dimensioned as public to the form. I populate the array on Form1_Load.
When I click the button btnReversingAnArray the first time all are sorted in reverse except for Wendy and it is the last item shown. ie..
(The book I am even shows an image of the list Box and their example also shows Wendy as the last item)
Richard
Michelle
Jay
Harriet
Wendy

Then I do nothing else except I click the button btnReversingAnArray again and then it displays correctly.
Wendy
Richard
Michelle
Jay
Harriet

Any suggestions as to why this is happening?
*****************

Public Class Forml
'Declare a form level aray
Private strFriends(4) As String

Private Sub Forml_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Populate the array
strFriends(0) = "Wendy"
strFriends(1) = "Harriet"
strFriends(2) = "Jay"
strFriends(3) = "Michelle"
strFriends(4) = "Richard"
End Sub

Private Sub btnReversingAnArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReversingAnArray.Click
'Clear the list
ClearList()
'Reverse the order - elements will be in descending(order)
Array.Reverse(strFriends)
'List your friends
AddltemsToList(strFriends)
End Sub

Private Sub ClearList()
'Clear the list
lstFriends.Items.Clear()
End Sub
 
Array.Reverse will just reverse the order of the elements. If you want it sorted you need to call Array.Sort.

VB.NET:
    Dim strFriends(4) As String

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        strFriends(0) = "Wendy"
        strFriends(1) = "Harriet"
        strFriends(2) = "Jay"
        strFriends(3) = "Michelle"
        strFriends(4) = "Richard"

        Array.Sort(strFriends)
    End Sub

    Private Sub ReverseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReverseButton.Click
        ClearList()
        Array.Reverse(strFriends)
        AddItemsToList(strFriends)
    End Sub

    Private Sub ClearList()
        FriendsList.Items.Clear()
    End Sub

    Private Sub AddItemsToList(ByVal arr() As String)
        FriendsList.Items.AddRange(arr)
    End Sub
 
Thanks, I had just finished a sorting routine and had sort on the brain.
Array.Reverse obviously just reverses the order but since I had sort in mind I was mistakenly looking for it to do a reverse sort.
Thanks
 
Back
Top