Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
    }

}
like image 480
Anthony Johnson Avatar asked Dec 20 '22 05:12

Anthony Johnson


2 Answers

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.

like image 136
Freelancer Avatar answered Jan 03 '23 13:01

Freelancer


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);
like image 27
Dave Bish Avatar answered Jan 03 '23 15:01

Dave Bish