I have a drop down in asp.net that I added some things to from the database. Also in the end I added some things manually. Now I need to sort these items in a quick and simple way. The drop down selected value is as number.
Is object link useful for my problem? If your answer is yes, please describe.
You can create a small utility method like this to sort the items of DropDownList.
public static void SortListControl(ListControl control, bool isAscending)
{
List<ListItem> collection;
if (isAscending)
collection = control.Items.Cast<ListItem>()
.Select(x => x)
.OrderBy(x => x.Text)
.ToList();
else
collection = control.Items.Cast<ListItem>()
.Select(x => x)
.OrderByDescending(x => x.Text)
.ToList();
control.Items.Clear();
foreach (ListItem item in collection)
control.Items.Add(item);
}
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
// Sort the DropDownList's Items by descending
SortListControl(MyDropDownList, false);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With