c# How to sort an array and put in a listbox?

1k views Asked by At

I am new to C# and I am trying to sort numbers from lowest to highest and then put them inside a ListBox. What I did so far is:

{
    int[] sortArray = new int[listBox2.Items.Count];
    for (int i = 0; i < listBox2.Items.Count; i++)
    {
        string sort = listBox2.GetItemText(i);
        sortArray[i] = int.Parse(sort);
    }
    int aantal = listBox2.Items.Count;

    listBox2.Items.Clear();

    Array.Sort(sortArray);

    listBox2.Items.Add(sortArray);
}

There are some numbers in the ListBox and when you press the button it should sort them. Can someone tell me what I do wrong?

5

There are 5 answers

0
Bv dL On BEST ANSWER

I found the answer, this is what I had to do. Thanks for your help :)

        int[] sortArray = new int[listBox2.Items.Count];
        for (int i = 0; i < listBox2.Items.Count; i++)
        {
            sortArray[i] = Convert.ToInt16(listBox2.Items[i]);
        }
        int aantal = listBox2.Items.Count;

        listBox2.Items.Clear();

        Array.Sort(soorteerArray);


        foreach (int value in sortArray)
        {
            listBox2.Items.Add(value);
        }
0
Jon Koivula On

Try this:

var newArray = sortArray.OrderByDescending(x => x).ToArray();
listBox2.Items.Add(sortArray);
0
Marc Cals On

I'm not in front of a computer with Visual Studio now to try it, but I think that something like this using Linq has to work

{
    List<int> items = listBox2.Items.select(i => int.Parse(i)).ToList();

    listBox2.Items.Clear();
    listBox2.Items.Add(items.OrderBy(i => i).ToArray());
}
0
Rosita Clerissa Serrao On

After you sort the array do this:

    foreach(int number in sortarray)
       listBox2.Items.Add(number);
0
Nameless One On

I think you need to add the items individually.

{
    int[] sortArray = new int[listBox2.Items.Count];
    for (int i = 0; i < listBox2.Items.Count; i++)
    {
        string sort = listBox2.GetItemText(i);
        sortArray[i] = int.Parse(sort);
    }
    int aantal = listBox2.Items.Count;

    listBox2.Items.Clear();

    Array.Sort(sortArray);

    foreach(var i in sortArray)
        listBox2.Items.Add(i);
}