保持ListBox排序,但始终将特定条目固定在顶部

Keep ListBox sorted, but with a particular entry always pinned to the top
2020-11-21
  •  译文(汉语)
  •  原文(英语)

我有一个包含国家(从Active Directory中获取)的列表框.我希望对列表进行排序,但是我也希望一个条目"全部"位于最顶部.

我怎样才能做到这一点?

速聊1:
将sorted属性设置为false.全部添加,添加排序的国家?除非我缺少什么.
速聊2:
谢谢大家,实际上我写错了.我有一个Combobox而不是Listbox :(但是作为下拉列表-我想它会类似吗?
解决过程1

如果要在后面的代码中绑定数据,则可以在索引0处插入一个Listitem.

ListItem myItem=new ListItem("ALL","value");
myListbox.Items.Insert(0, myItem);
解决过程2

在绑定到您的ListBox之前,我将首先对列表项进行排序.取决于您的数据源是什么,例如DataTable,List,Dictionary等,有几个选项可以执行此操作.要插入项目,请在下面使用代码.

lstCountries.Items.Insert(0, new ListItem("All", "0"));
解决过程3

加载数据(即国家/地区)后,按如下所示添加ListItem:

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

在这里,您可以考虑如果选择文本为"全部"的列表框,则应采取哪种措施.

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?

Talk1:
set the sorted property to false. Add All, add the sorted countries? Unless I'm missing something..
Talk2:
Thank you all, actually I wrote it wrong. I have a Combobox not a Listbox :( but as a dropdownlist - I guess it would work similar?
Solutions1

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);
Solutions2

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"));
Solutions3

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.

转载于:https://stackoverflow.com/questions/28309764/keep-listbox-sorted-but-with-a-particular-entry-always-pinned-to-the-top

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入