views:

17

answers:

2

I'm using a WinForms TextBox control for logging. It's been set as multiline with scrollbars. I'm inserting text by using:

textBox.Text += logMessage;

The scrollbar does not automatically follow with the latest log entry. Is there a way to do this?

A: 

Set the TextBox's SelectionStart property to the length of the text, then call ScrollToCaret.

icktoofay
I tried both those methods independently but never together. Thank you!
Alex Angas
+1  A: 

I'm late to the party, but the thing to be careful when logging like this is the length of your text field. You want to trim the head of it every so often (but not too often...). The strategy I've used is to use a max character limit, say 5000, and when that text reaches double the limit, cut it down to the limit.

string LimitText(string Text)
{
    int textLimit = 5000;
    //let the field grow to double the limit, then chop it in half
    if (Text.Length > textLimit * 2)
    {
        Text = Text.Substring(Text.Length - textLimit, textLimit);
    }
    return Text;
}

The double limit thing is there to reduce the occurrence of substring operations. Also, this is really only an issue if you use this in a long running programs that continuously add to the text field. (Yes, I also log to a text file and normally use that for debugging. This is more for quick diagnostics...)

Tim Coker
Great advice, thank you!
Alex Angas