only My site

Monday, July 7, 2008

Sort Dropdown List

Hi...

There is no option in Dropdown server control to Sort the list items as like Array sort method. So a small workaround need to do this. Here is a simple sample.

ddlModelType.DataValueField = "key";
ddlModelType.DataTextField = "value";
ddlModelType.DataSource = strDict;
ddlModelType.DataBind();
SortDropDown(ddlModelType);
ddlModelType.Items.Insert(0, new ListItem("Select", "-1"));

private void SortDropDown(DropDownList dd)
{
ListItem[] ar = new ListItem[dd.Items.Count];
long i = 0;
foreach (ListItem li in dd.Items)
{
// ERROR: Not supported in C#: ReDimStatement
ar[i] = li;
i += 1;
}
ListItem[] ar1 = ar;
Array.Sort(ar1, new ListItemComparer());
dd.Items.Clear();
dd.Items.AddRange(ar1);
//dd.Items.AddRange(ListItem ar1);
}

class ListItemComparer : IComparer
{
int System.Collections.IComparer.Compare(object x, object y)
{
ListItem a = (ListItem)x;
ListItem b = (ListItem)y;
CaseInsensitiveComparer c = new CaseInsensitiveComparer();
return c.Compare(a.Text, b.Text);
}
}

No comments: