views:

43

answers:

2

I am writing text to a multi-line text box using data from the serial port. Currently it writes each new line below the previous line, so eventually the newest lines of text are off the screen, and user must scroll down to view them. How can I change the code so it writes each new line above rather than below the previous line of text? I'm developing the program for Windows Mobile 6 devices using C# in VS2008. I know this is probably a simple solution, but I'm new to C# and can't seem to figure out what I'm doing. Thanks in advance!

Update:

This is the closest to what I was trying to accomplish:

private void terminalText(object o, EventArgs e)
    {
        tbTerminal.Text += rawString;
        tbTerminal.Select(tbTerminal.TextLength, 0);
        tbTerminal.ScrollToCaret();
    }

It doesn't write the next line above the previous line as I was hoping, but it automatically focuses the latest written text so you don't have to use the scroll bar to view the most recent port data. I appreciate all the help!

A: 

I think you should be able to just plunk the new line of text in front of all the previous text like this:

field.Text = receivedLine + "\r\n" + field.Text

Another option is to always add the text on to the end and just scroll the text field to the end:

        field.Text += receivedLine + "\r\n"
        var isNotEmpty = field.TextLength > 0;
        if (isNotEmpty)
        {
            field.Select(field.TextLength - 1, 0);
            field.ScrollToCaret();
        }

This is fine for a reasonable amount of text that's being received at a reasonable frequency. If you start using large chunks of text or tons of updates, you may have to optimize further.

Don Kirkby
You don't need the empty string checking as you can simply do what I've stated in my answer (aka not take away 1) and it will scroll to the end and not error if the textbox's text field is empty (as it will go to 0)
Blam
Thanks, @Blam, I'll see if that lets me simplify my code.
Don Kirkby
A: 

You could always select the last character and then scroll to the caret, I'm not too sure if it's any different with the compact framework, but with regular text box control:

textBox.Select(textBox.TextLength, 0);
textBox.ScrollToCaret();
Blam
Thanks! This isn't quite what I was going for, but it's definitely an alternative solution. Very much appreciated!
Chris