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());
}
}
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With