Array values into list box
37,575
Solution 1
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.
Solution 2
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);
Author by
Anthony Johnson
Updated on November 28, 2020Comments
-
Anthony Johnson over 3 years
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()); } }
-
Anthony Johnson almost 11 yearsAh Thank you! I see what i did now, when i clear the listbox items listbox.items.count will reset to 0 :) thank you!