views:

86

answers:

5

I want to get an bunch of items from a list box, add them to an array, sort it, then put it back into a different listbox. Here is what I have came up with:

ArrayList q = new ArrayList();
        foreach (object o in listBox4.Items)
            q.Add(o);
        q.Sort();
        listBox5.Items.Add(q.ToString());

But it doesnt work. Any ideas?

+2  A: 
ArrayList q = new ArrayList(); 
foreach (object o in listBox4.Items) 
        q.Add(o);
} 
q.Sort(); 
listBox5.Items.Clear();
foreach(object o in q){
    listBox5.Items.Add(o); 
}
HCL
cheers dude, great help. How could I do the same thing using a for loop? Im new and just learning
Codie Vincent
@Codie Vincent: do you mean: for(int i=0;i<listBox.Items.Count;i++){q.Add(listBox.Items[i]);} Look at the other posts and comments because I directly answered to your question without trying to show alternatives. But there is much room for optimization on what you're doing with the list.
HCL
+1  A: 

Add the items to array and close the loop. Then sort the array values and bind it to listbox

Bala
A: 

Try AddRange

    ArrayList q = new ArrayList();

    foreach (object o in listBox4.Items)
        q.Add(o);
    q.Sort();

    listBox5.Items.AddRange(q.ToArray());
Branimir
A: 

You could just use the ListBox.Sorted built in functionality

  foreach (object o in listBox4.Items)
  {
    listBox5.Items.Add(o);
  }
  listBox5.Sorted = true;

Setting ListBox5.Sorted=true will ensure that the items in the listbox are sorted and any subsequent items added to the listbox will be added in the correct order.

Of course this assumes that you have simple sort requirements as suggested by your example.

Chris Taylor
A: 

If you are using .Net3.5 use linq to finish this task.Here i used list to convert and sorted

        var list = ListBox1.Items.Cast<ListItem>().Select(item => item.Value).ToList();
        list.Sort();

        ListBox2.DataSource =list;
        ListBox2.DataBind();
anishmarokey