How to sort an array list

Posted by Sharpcnet under C# on 12/25/2013 | Points: 10 | Views : 2696 | Status : [Member] | Replies : 5
There are 2 listboxes to exchange items. Each list item has text and value properties eg: "Branch",1 ; "Leaves",23,...etc After adding an item from listbox2 to listbox1, I would like to sort listbox1.

lb1 and lb2 are the listboxes.
protected void btnRemove_Click()
{
if(lb2.Items.count > 0)
{
if(lb2.selectedindex >=0)
{
ListItem li = lb2.selecteditem;
lb1.items.add(li);

//sort
List<ListItem> al = new List<ListItem>();
foreach(listitem l in lb1.items)
{
al.Add(l);
}
lb1.items.clear();
al.sort();
lb1.Datasource=al;
lb1.databind();
}
}
}


At al.sort(); it gives an error - "Failed to compare 2 elements in the array". How should I correct this.




Responses

Posted by: vishalneeraj-24503 on: 12/25/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
What you can do, just add your list box items into Array List first,then Sort array list using Sort() method of an Arraylist,then loop through the array list and then add into another list box.Then you will have sorted name in another listbox.

Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: vishalneeraj-24503 on: 12/25/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Please refer:-
http://www.realtimeasp.com/post/How-To-Sort-The-ListItems-In-The-List-Box
http://mrbool.com/working-with-listbox-using-asp-net-and-csharp/25298
http://www.vbasic.net/how-to-sort-items-in-a-listbox-in-visual-basic-net/

Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sharpcnet on: 12/25/2013 [Member] Starter | Points: 25

Up
0
Down
ArrayList al = new ArrayList();
for(int i=0;i<lb1.items.count;i++)
{
al.Add(lb1.Items[i].ToString());
}
lb1.items.clear();
al.sort();
lb1.datasource=al;
lb1.databind();


It did not error sort now, but did at 'Databind(); - "Listitem does not contain property formname' But I have DataTextfield="formname" Datavaluefield="formid"...same for both listboxes

what is wrong in the first method i wrote?

Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: vishalneeraj-24503 on: 12/25/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Instead of taking Arraylist you can take Hash Table,it will have key and value pair means key will be your formname and value will be your form id or you can also take sortedlist class.

Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: vishalneeraj-24503 on: 12/25/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down

you have missed to take text or value in lb1.Items[i],you should take lb1.Items[i].Text or lb1.Items[i].Value as shown

for(int i=0;i<lb1.items.count;i++)

{
al.Add(lb1.Items[i].Text .ToString());
}


Add Text in lbl.Items[i].Text

Sharpcnet, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response