Jose M.
Jose M.

Reputation: 2340

Building a collection of buttons and sorting by text

I have a collection of buttons on a panel, I want to be able to build a collection of those buttons and then sort the buttons by the text on the button. However, I am stuck. This is what I have so far, but I can't figure out how to sort.

   Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click

        Dim btn1 As Control
        Dim btnArray(0 To 3) As Button

        btnArray(0) = btnAll
        btnArray(1) = btnWine
        btnArray(2) = btnBeer
        btnArray(3) = btnNonAlcoholic

        For Each btn1 In btnArray




        Next


    End Sub

Upvotes: 0

Views: 69

Answers (2)

Victor Zakharov
Victor Zakharov

Reputation: 26434

Using LINQ:

btnArray = btnArray.OrderBy(Function(btn) btn.Text).ToArray

Upvotes: 0

Jens
Jens

Reputation: 6375

You can use a simple manual bubble sort:

Dim Changed as Boolean = False
Do
  Changed = False
  For i = 0 to btnArray.Count - 2
     If btnArray(i).Text > btnArray(i+1).Text Then '< > work for strings as well and they check 'position' in the alphabet. So "A" < "B" and so on
        'If order is wrong, switch the two buttons
        Dim temp as Button = btnArray(i+1)
        btnArray(i + 1) = btnArray(i)
        btnArray(i) = temp
        Changed = True
     End If
   Next
 'Do this until no more switches are necessary
Loop Until Changed = False

This will order your buttons and is reasonably fast for low numbers of buttons. You could use a list and a custom IComparer object as well and simply call List.Sort with the custom comparer. See here for example implementations of this approach for a similar problem: http://msdn.microsoft.com/en-us/library/cfttsh47%28v=vs.110%29.aspx

Upvotes: 1

Related Questions