user1930845
user1930845

Reputation:

RichTextbox write in place to current line

Clarification: I want to output line of text to the same "position" in a RichTextBox, replacing the previous line.

In C# Windows Forms Application trying to use RichTextBox for displaying messages. Most of the messages are appended, so that is fine but at one point in the program it has a counter, showing the amount of rows processed. For example like this:

Processed: 001 Records.

etc

well ... I don't need it to fill the RichTextBox with a thousands of lines like this:

Processed: 001 Records.

Processed: 002 Recoeds.

Instead I am trying to move the Caret to a start of the line and write the line again. Probably need to remove the previous line in a RichTextBox. Can't figure out how to always write to the same last line in RichTextBox.

I tried to use SelectionStart and ScrollToCaret() that did not work.

Upvotes: 1

Views: 1835

Answers (2)

Steve
Steve

Reputation: 216293

You could try something like this (rtb is your RichTextBox variable)

// Get the index of the last line in the richtextbox
int idx = rtb.Lines.Length - 1;

// Find the first char position of that line inside the text buffer
int first = rtb.GetFirstCharIndexFromLine(idx);

// Get the line length
int len  = rtb.Lines[idx].Length;

// Select (Highlight) that text (from first to len chars)
rtb.SelectionStart = first;
rtb.SelectionLength = len;

// Replace that text with your update
rtb.SelectedText = "Processed: " + recordCount + " Records.";

No error handling added, but you could add some checks to be sure to stay inside the text buffer

Upvotes: 1

cbr
cbr

Reputation: 13652

One solution would be to store the current text before you start processing:

string oldText = richTextBox.Text;

for (int i = 0; i < X; i++)
{
    // process stuff
    richTextBox.Text = oldText + Environment.NewLine + "Processed: " + i + " Records.";
}

I believe that this method disregards the RTF data though, so you might use RichTextBox.Rtf instead.

Upvotes: 1

Related Questions