Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I have 2 listboxes

the first one is populated by a Oracledatabase and I sorted it by my sql query(order by)

the second must be populated by selecting items from the first one

that's no problem but I want that the second listbox should be sorted also

 

and when i retrieve items from the second i want to put them sorted in the first one

 

do i have to use an array? or are there other means?

  • *Experts*
Posted

You could set the Sorted property to true if you just want simple alphabetic order. If you want a different order, you will need to write a class which derives from IComparer and use it with the Sort method of af an array. An IComparer is just an object which compares two objects and returns whether [Thing A] is less than, equal to, or greater than [Thing B] so it knows where to put it in the array.

 

Note that if you want to use a different IComparer, you will need to use an array to sort it and then add to the listbox.

Posted (edited)

For a web-form you can do this:

//GENERIC FUNCTION FOR SORTING A LIST BOX
private void SortListBox(ListBox currList)
{
//COPY THE MEMBERS OF THE LISTBOX INTO AN ARRAY LIST
ArrayList arraylist = new ArrayList();
foreach(ListItem li in currList.Items)
{
arraylist.Add(li);
}
arraylist.Sort(new ListObject(ListObject.Directions.ascending)); //SORT THE LIST - ASCENDING

//REMOVE THE EXISTING ITEMS FROM LISTBOX
currList.Items.Clear(); 

//RE-ADD THE SORTED ITEMS TO THE LISTBOX
for(int i = 0 ; i < arraylist.Count ; i++)
{
currList.Items.Add((ListItem) arraylist[i]);
}
currList.SelectedIndex = -1; //ENSURE NO SELECTED ITEM
	}

	

//*** NEED THIS FOR ARRAY-LIST SORTING: ***
private class ListObject : IComparer
{
public enum Directions : int { ascending = 1, descending = (-1) };
private int direction = (int) ListObject.Directions.ascending;

public ListObject() {}
public ListObject(Directions direction) { 
 this.direction = (int) direction; 
}

public int Compare(object x, object y)
{
string xstring = ((ListItem) x).Text;
string ystring = ((ListItem) y).Text;
return xstring.CompareTo(ystring) * this.direction;
}
}
	//*******************************************[

Edited by Volte

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...