C# 如何将项目添加到ListBox中列表的开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/819891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add item to the beginning of the list in ListBox?
提问by kyrisu
Is there a way to add item to a WinForms ListBox, to the beginning of the list without rewriting entire list in a loop?
有没有办法将项目添加到 WinForms ListBox,添加到列表的开头,而无需在循环中重写整个列表?
Other way to solve my problem would be to display ListBox in reverse order (last item on the top) but I don't know how to do it.
解决我的问题的其他方法是以相反的顺序显示 ListBox(顶部的最后一项),但我不知道该怎么做。
My ListBox control is used as a log viewer where the most recent entry should be on the top.
我的 ListBox 控件用作日志查看器,其中最近的条目应位于顶部。
回答by Razzie
If I understand correctly, can't you use the Insert(int index, object item)
method? For example:
如果我理解正确,您不能使用该Insert(int index, object item)
方法吗?例如:
myListBox.Items.Insert(0, "First");
This inserts "First" as the first item of the listbox.
这将插入“First”作为列表框的第一项。
回答by atfergs
You should be able to set the sort order in your data source if you're timestamping the log events.
如果您为日志事件添加时间戳,您应该能够在数据源中设置排序顺序。
回答by TimothyP
One option might be to use the .Sort() method of the ListBox http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.sort.aspx
一种选择可能是使用 ListBox http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.sort.aspx的 .Sort() 方法
The other of course is to put your items in a generic list and add/remove items from that list instead of directly to the ListBox. Use the list as a datasource for your ListBox.
另一个当然是将您的项目放在通用列表中,然后从该列表中添加/删除项目,而不是直接添加到 ListBox。将该列表用作 ListBox 的数据源。
回答by Peter
I have no scientific proof to back me up here but I think a textbox is more performant in handling log visualization. You can also easily setup autoscrolling and if you would want to copy something, it would not require any coding.
我没有科学证据来支持我,但我认为文本框在处理日志可视化方面的性能更高。您还可以轻松设置自动滚动,如果您想复制某些内容,则不需要任何编码。