By Berossus
I recently needed to sort data in a web.ui.listbox and had to do a bit of research.
Listboxes are comprised of ListItems. ListItems consist of Text, which is displayed to the user, and a Value which is the primary key reference for the object. The steps required are ...
1. Create an ArrayList to store your ListItems.
2. Sort the ArrayList.
3. Copy the ArrayList to the ListBox.
Sorting requires a derivative of the ICompare interface. The Compare() method evaluates a ListItem comparison returning an integer with zero == an exact match or 1 or (-1) if one or the other is evaluated with a higher or lower pecking order.
The code fragment looks like this.
using System;
using System.Collections;
// create a derative from IComparer as a nested class within your page.
// The CompareTo() method returns either 0, 1, or (-1). We multiply the value
// it returns by (-1) for sorting in descending order.
// We do this by setting the ascending/descending enumerator to either 1 or (-1).
// the sort is implemented from the Array.Sort(new ListObject(ListObject.Directions.descending)).
// Here, we are passing an instance of our ListObject. We tell the constructor
// if we are sorting in either ascending or descending order.
namespace MyCo.MyPo
{
public class PageSearch02 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label LabelMessage;
protected System.Web.UI.WebControls.ListBox listbox;
protected OleDbConnection connection;
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;
}
}
private void Page_Load(object sender, System.EventArgs e)
{
try
{
String sql = "select * from Documents where isActive = 'T' ";
// the best way to sort the listbox is to sort the query ...
// as in "select * from tablename order by fieldname ".
// there are many cases where you do not have this luxury,
// such as in cases where the data comes from sources other than the database.
// you may need to use the IComparer interface,
// if you want to keep the listbox in sorted order at all times,
// and/or the user will be adding/deleting or changing data affecting the listbox.
OleDbCommand localcommand = new OleDbCommand();
localcommand.Connection = this.connection;
localcommand.CommandText = sql;
localcommand.Parameters.Clear();
OleDbDataAdapter localadapter = new OleDbDataAdapter(localcommand);
DataSet localdataset = new DataSet("Documents");
localadapter.Fill(localdataset,"Documents");
// create an ArrayList as a temporary holding buffer.
// make the arraylist variable a local variable,
// so that it falls out of scope after it gets copied to the listbox.
ArrayList arraylist = new ArrayList();
// populate the arraylist from your Dataset().
// The ArrayList is a collection of ListItems as is a ListBox control.
foreach(DataRow row in localdataset.Tables[0].Rows)
{
ListItem listitem = new ListItem();
listitem.Text = row["subject"].ToString();
listitem.Value = row["recorduid"].ToString();
arraylist.Add(listitem);
}
// sort the ArrayList using the ListObject : IComparer implementation above.
// this is where the work gets done.
arraylist.Sort(new ListObject(ListObject.Directions.descending));
// copy the ArrayList to the Listbox.
// you could cheat here and reverse populate for descending order.
for(int i = 0 ; i < arraylist.Count ; i++)
this.listbox.Items.Add((ListItem) arraylist[i]);
// check the results and let the user know if there is no data.
// all of my web pages include a label control (named LabelMessage)
// for the specific purpose of displaying errors and other pertinent messages to the user.
if (this.listbox.Items.Count >= 1)
{
this.listbox.Visible = true;
this.listbox.SelectedIndex = 0;
}
else
{
this.listbox.Visible = false;
this.LabelMessage.Font.Bold = true;
this.LabelMessage.Text = "Sorry - no documents were found based on the search criteria presented.";
}
}
catch(OleDbException c)
{
this.LabelMessage.Text = "PageSearch02.SearchDocuments: OleDbException Error: " + c.Message;
}
}
}
}