Something like that:
ListBox ListBoxLog = new ListBox();
internal void Log(string message) {
ListBoxLog.Items.Add(message);
ListBoxLog.SelectedIndex = ListBoxLog.Items.Count - 1;
}
You may also want to make it thread-safe, more exactly, to make it possible to add message from non-UI thread. It's just a bit more complex:
ListBox ListBoxLog = new ListBox();
static void Log(ListBox listBox, string message) {
listBox.Items.Add(message);
listBox.SelectedIndex = listBox.Items.Count - 1;
}
internal void Log(string message) {
if (ListBoxLog.InvokeRequred)
ListBoxLog.Invoke(new Action<ListBox, string>((listBox, msg)=>{
Log(listBox, msg);
}), ListBoxLog, message);
else
Log(ListBoxLog, message);
}
Finally, you may want to store items of any type in a list box, not just strings. It could be very useful to store additional information in the items, such as type of message, topic, exception information, etc. On selection events of the list box, you could get this data from an item and show it in, say
PropertyGrid
in the style of master-detail view.
You can do it, but the problem will be: what will be presented as a text of view item? The answer is simple: whatever is returned by the method
ToString
. For this purpose, you just need to override
object.ToString
in the type of a list item to present appropriate part of data in the form of one short string.
—SA