Random sort of listBox index?
Hello!
I am currently trying to implement an option to sort a listBox's (lbImages) items in a random way. Each item of the listBox represent a string, and I wish for these to occur, everytime it's called, in a new and random order.
How can I accomplish this?
Here is my current code, but I just can't get it to work right:
Code:
private void cbxSort_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxSort.Text == "Alphanumerical")
{
lbImages.Sorted = true;
}
else if (cbxSort.Text == "Random")
{
Random random = new Random();
List<string> randomList = new List<string>();
for (int i = 0; i < lbImages.Items.Count; i++)
{
randomList.Add(lbImages.Items.IndexOf(i).ToString());
}
lbImages.Items.Clear();
for (int i = randomList.Count; i > 0; i--)
{
iNewRandomIndex = random.Next(0, randomList.Count - 1);
lbImages.Items.Add(randomList.IndexOf(i)); // Have a problem in this line
randomList.RemoveAt(iNewRandomIndex);
iLastRandomIndex = iNewRandomIndex;
}
}
}
Re: Random sort of listBox index?
vb.net Code:
Private randomiser As New Random
Private Sub RandomiseListBox()
Dim count As Integer = Me.ListBox1.Items.Count
Dim item As Object
For index As Integer = 0 To count - 2 Step 1
item = Me.ListBox1.Items(Me.randomiser.Next(index, count))
Me.ListBox1.Items.Remove(item)
Me.ListBox1.Items.Insert(index, item)
Next index
End Sub
Re: Random sort of listBox index?
D'oh! Here's the C# version:
Code:
private Random randomiser = new Random();
private void RandomiseListBox()
{
int count = this.listBox1.Items.Count;
object item;
for (int index = 0; index <= count - 2; index++)
{
item = this.listBox1.Items[this.randomiser.Next(index, count)];
this.listBox1.Items.Remove(item);
this.listBox1.Items.Insert(index, item);
}
}
Re: Random sort of listBox index?
Ah, thank you!
The problem is now solved.
Cheers,
Zolomon