How to add item to the beginning of the list in ListBox?

北城余情 提交于 2019-12-04 09:59:06

问题


Is there a way to add item to a WinForms ListBox, to the beginning of the list without rewriting entire list in a loop?

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.

My ListBox control is used as a log viewer where the most recent entry should be on the top.


回答1:


Use the Insert method on the items of your ListBox.




回答2:


If I understand correctly, can't you use the Insert(int index, object item) method? For example:

myListBox.Items.Insert(0, "First");

This inserts "First" as the first item of the listbox.




回答3:


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

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.




回答4:


You should be able to set the sort order in your data source if you're timestamping the log events.




回答5:


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.



来源:https://stackoverflow.com/questions/819891/how-to-add-item-to-the-beginning-of-the-list-in-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!