tags:

views:

1362

answers:

5

Hi,

Is there a way to add item to ListBox (C#), 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.

Thanks in advance :)

+2  A: 

Use the Insert method on the items of your ListBox.

bruno conde
Thanks :) I see I have much to learn about C# :D
kyrisu
+1  A: 

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

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

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

Razzie
+1  A: 

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

orthod0ks
A: 

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.

TimothyP
A: 

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.

Peter
I have already solved my problem (by using insert :P) but just for clarification - I am using listbox cause i need an easy way to add items and custom colors for every message (like error, success and so on) and I have already wrote DrawItem handler for listbox :)
kyrisu