Keep ListBox sorted, but with a particular entry a

2019-09-02 02:09发布

问题:

I have a ListBox filled with Countries (which I take from the Active Directory). I want the list to be sorted, but also I want one entry "All" to be at the very top.

How can I do this?

回答1:

If you are binding the data in code behind you can insert a Listitem at index 0.

ListItem myItem=new ListItem("ALL","value");
myListbox.Items.Insert(0, myItem);


回答2:

I would sort the list items first before binding to you ListBox. There are several options for doing this depending on what your data source is i.e. DataTable, List, Dictionary etc. To insert an item use code below.

lstCountries.Items.Insert(0, new ListItem("All", "0"));


回答3:

After you load the data (i.e Countries), add the ListItem as follows:

myListbox.Items.Add(new ListItem() { Text = "All", Value = "" });
myListbox.SelectedIndex = 0; //This line will selected the first item on your ListBox.

Here, you might consider which action take if the ListBox with text "All" is selected.