1

I have a listbox and I want to sort each item in that listbox from a-z and assign those code in a button. Do i need to assign the array to the listbox? and then use a loop ?

This is what I did:

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

    for (int i = 0; i < sort.Length; i++)
    {
        sort[i] = cartListBox.Items[i].ToString();
        Array.Sort(sort);
    }
}

However, when I click the button, it doesnt do anything.

3
  • you are sorting the string array. Do you expect the list box to be sorted? Commented Sep 30, 2013 at 3:13
  • You should sort outside the loop. Also you should sort listbox separately. Commented Sep 30, 2013 at 3:16
  • yeah.... do i need to assign the array to the value of the listbox?? Commented Sep 30, 2013 at 3:19

2 Answers 2

3

You need to sort that outside the loop.

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

    for (int i = 0; i < sort.Length; i++)
    {
        sort[i] = cartListBox.Items[i].ToString();
    }
    Array.Sort(sort);

    for (int i = 0; i < sort.Length; i++)
    {
        // reset the order for the cartListBox collection according to the sort array, if needed
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your ListBox has a Sorted Property that you can use to enable Sorting

cartListBox.Sorted = true;

From above MSDN Link:

Use the Sorted property to automatically sort strings alphabetically in a ListBox. As items are added to a sorted ListBox, the items are moved to the appropriate location in the sorted list. When adding items to a ListBox, it is more efficient to sort the items first and then add new items.

A ListBox with its Sorted set to true should not be bound to data using the DataSource property. To display sorted data in a bound ListBox, you should bind to a data source that supports sorting and have the data source provide the sorting.

1 Comment

There is a Sorted statement see the link that I added, I also am assuming winforms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.