问题
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