0

Ok, so i have to sort a listbox (randomListBox) using an array (defaultArray) for university, but the instructions and tutors aren't much help, so this is what i had using the instructions but it doesn't work.

    string[] defaultArray = new string[randomListBox.Items.Count];

    for (int i = 0; i < randomListBox.Items.Count; i++)
    {
        defaultArray[i] = randomListBox.Items[i].ToString();
    }

    Array.Sort(defaultArray);

    randomListBox.Items.Clear();

    for (int i = 0; i < randomListBox.Items.Count; i++)
    {
        randomListBox.Items.Add(defaultArray[i].ToString());
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
CalumM
  • 13
  • 1

3 Answers3

2

Your second for loop never runs because you have deleted all the items in listbox therefore the items count is 0. Try:

for (int i = 0; i < defaultArray.Length; i++)
{
    randomListBox.Items.Add(defaultArray[i]);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

Think about the second occurrence of this line:

for (int i = 0; i < randomListBox.Items.Count; i++)

Are you sure that's what you meant?

What do you actually want to loop through?

(I'm not providing the answer directly as this is a homework question.)

Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
0

In the last for loop, you are using randomListBox.Items.Count rather than defaultArray.Length.

for (int i = 0; i < defaultArray.Length; i++)
{
    randomListBox.Items.Add(defaultArray[i].ToString());
}
Recourse
  • 46
  • 8