private class SortListItem : IComparer<ListItem> { public int Compare(ListItem x, ListItem y) { return String.Compare(x.Value, y.Value); } }
2. Use this class in your method.
private void SortListBoxItems(ListBox listBoxObject) { List<ListItem> ListToSort = new List<ListItem>(); foreach (ListItem lbItem in listBoxObject.Items) ListToSort.Add(lbItem); ListToSort.Sort(new SortListItem()); //use it at here listBoxObject.Items.Clear(); listBoxObject.Items.AddRange(ListToSort.ToArray()); } How about descending? Just change the class you created in step 1 to like this: private class SortListItem : IComparer<ListItem> { public int Compare(ListItem x, ListItem y) { return 0 - String.Compare(x.Value, y.Value); } }
This works fine on .Net 4.0.
Thank you!
ReplyDeleteI'm very glad to see your code!
Y.Yamamoto, from Japan.
Thanks Kenny,
ReplyDeleteBrilliant code.
Ahmed.