We help IT Professionals succeed at work.
Get Started

Randomize 'shuffle' Listbox Items on button click (winform) vb.2003

Last Modified: 2012-05-09
Hi Experts,

I've been tearing my hair out trying to achieve what is probably a simple task. All's I want to do is click a button and change the order of items in a Listbox. this must loop on button click (i.e. if the button clicks again, it shuffles)

I have come across many examples and have tried them all... they all seem to do slightly different tasks, but not want i want :(

Can someone please help?
' I tried this one to start. It seems to move the listbox item out of the Listbox and move it to a Textbox
  Private R As New Random

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If ListBox1.Items.Count > 0 Then
            Dim index As Integer = R.Next(0, ListBox1.Items.Count)
            TextBox1.Text = ListBox1.Items(index)
        End If
        If ListBox1.Items.Count = 0 Then
            Button1.Enabled = False
        End If
    End Sub

' Then I tried thie code which changes the order of the highlight - not the actual items :(

Dim listcount As Integer = ListBox1.Items.Count
        Dim index As Integer
        Dim temp As Object
        Dim r As New Random

        For i As Integer = 0 To listcount - 1
            index = r.Next(0, listcount)
            temp = ListBox1.Items(i)
            ListBox1.Items(i) = ListBox1.Items(index)
            ListBox1.Items(index) = temp

Open in new window

Watch Question
Full stack Software Engineer
This problem has been solved!
Unlock 1 Answer and 35 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE