Anthony Johnson
Anthony Johnson

Reputation: 273

Array values into list box

I have the following code.

I am trying to insert values into a listbox, and then be able to resort the values by alphabetical order and re display them in the same listbox. For some reason code doesn't work (no errors - just when i push the button the listbox clears)

protected void sortButton_Click(object sender, ImageClickEventArgs e)
{
    string[] movieArray = new string [cartListBox.Items.Count];

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

    Array.Sort(movieArray);

    cartListBox.Items.Clear();

    for (int i = 0; i < cartListBox.Items.Count; i++)
    {
        cartListBox.Items.Add(movieArray[i].ToString());
    }

}

Upvotes: 5

Views: 43971

Answers (4)

Herbert
Herbert

Reputation: 85

To add movieArray to listbox use AddRange

  • carListBox.Items.AddRange(movieArray);

To sort just set sorted =true

  • carListBox.Sorted=true;

Complete code is below

  • carListBox.Items.AddRange(movieArray);
  • carListBox.Sorted=true;

Upvotes: 0

Dave Bish
Dave Bish

Reputation: 19646

You can avoid all that looping, and your bug, by doing this in a more modern way:

var items = cartListBox.Items
    .Select(item => item.ToString())
    .OrderBy(x => x);

cartListBox.Items.Clear();

cartListBox.Items.AddRange(items);

Upvotes: 1

Carlos Landeras
Carlos Landeras

Reputation: 11063

cartListBox.Items.Count // is 0 length

you are doing in the previous step:

cartListBox.Items.Clear(); 

Upvotes: 0

Freelancer
Freelancer

Reputation: 9074

I think problem is in last loop.

Do that like follows:

cartListBox.Items.Clear();

    for (int i = 0; i < movieArray.Length; i++)
    {
        cartListBox.Items.Add(movieArray[i].ToString());
    }

When you are clearing cartListBox.Items.Clear();, it should not be taken for loop counter like, for (int i = 0; i < cartListBox.Items.Count; i++)

cartListBox.Items.Count was creating problem.

Upvotes: 10

Related Questions