Friday, January 22, 2010

Sorting a Dropdownlist!!

by Electronic Screw

Hi,
Today while workin on a project, i came across a situation where i need to sort the item in a dropdownlist. Unfortunately, there is no sort method available to the Dropdownlist and other ListItem containers. So i need to write it of my own, the functionality to sort the items. Here is code for you, if any needs!
-- Write these 2 classes in any of your class file.
-- Usage General.SortDropDownList(dropdownlist);

1        public class General {
2 public static void SortDropDownList(DropDownList ddlList) {
3 ArrayList arl = null;
4 if (ddlList.Items.Count > 0) {
5 arl = new ArrayList(ddlList.Items.Count);
6 foreach (ListItem li in ddlList.Items) {
7 arl.Add(li);
8 }
9 }
10 arl.Sort(new ListItemComparer());
11 ddlList.Items.Clear();
12 for (int i = 0; i < arl.Count; i++) {
13 ddlList.Items.Add(arl[i].ToString());
14 }
15 }
16 }
17
18 public class ListItemComparer : IComparer {
19 #region IComparer Members
20 public int Compare(object x, object y) {
21 ListItem lix = (ListItem)x;
22 ListItem liy = (ListItem)y;
23 CaseInsensitiveComparer c = new CaseInsensitiveComparer();
24 return c.Compare(lix.Text, liy.Text);
25 }
26 #endregion
27 }

Thanks

No comments:

Post a Comment