Array values ​​in the list box

Hi guys there is currently the following code

I am trying to insert values ​​into a list and then be able to apply the values ​​alphabetically and re-display them in the same list. For some reason, the code doesn't work (no errors - only when I click the button to clear the list)

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()); } } 
+4
source share
3 answers

I think the problem is in the last cycle.

Do the following:

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

When you clear cartListBox.Items.Clear(); , it should not be taken as a loop counter, for example, for (int i = 0; i < cartListBox.Items.Count; i++)

cartListBox.Items.Count was creating a problem.

+8
source
 cartListBox.Items.Count // is 0 length 

which you do in the previous step:

 cartListBox.Items.Clear(); 
0
source

You can avoid this whole cycle and your mistake by making this in a more modern way:

 var items = cartListBox.Items .Select(item => item.ToString()) .OrderBy(x => x); cartListBox.Items.Clear(); cartListBox.Items.AddRange(items); 
0
source

Source: https://habr.com/ru/post/1482363/


All Articles