Problem removing Text from RichTextbox

  • Thread starter Thread starter Joe Cool
  • Start date Start date
J

Joe Cool

I am trying to remove some text from a RichTextbox. Let's say it
contains something like:

Line 1
Line 2

"Line 1" is bold, "Line 2" is not. If I remove "Line 1" with:

richTextbox.Text = richTextbox.Text.Replace("Line 1", "");

it removes the text "Line 1" but now Line 2 is bold!!!

How can I remove a bolded "Line 1" without "Line 2" assuming "Line
1"'s bold attribute?
 
I've tried your example and it's truly setting Line2 in bold. Try following...
If you are selecting the text manually, use this:

string selectedText = rtb.SelectedText;

If you are selecting the text programatically, use this(as in your example):

string selectedText = "Line 1";

And use following code to remove the text:

if (selectedText.Length > 0)
rtb.SelectedText = "";
else
{
int caretPosition = rtb.SelectionStart;
if (caretPosition != rtb.TextLength)
{
rtb.Select(caretPosition, 1);
rtb.SelectedText = "";
}
}

Hope this helps.
 
I've tried your example and it's truly setting Line2 in bold. Try following...
If you are selecting the text manually, use this:

string selectedText = rtb.SelectedText;

If you are selecting the text programatically, use this(as in your example):

string selectedText = "Line 1";

And use following code to remove the text:

if (selectedText.Length > 0)
            rtb.SelectedText = "";
            else
            {
                int caretPosition = rtb.SelectionStart;
                if (caretPosition != rtb.TextLength)
                {
                    rtb.Select(caretPosition, 1);
                    rtb.SelectedText = "";
                }
            }

Hope this helps.

Well, it helped in the sense it gave me some ideas. I was able to
accomplish this with the following code:

rtb.Find("Line 1");
rtb.Select();
rtb.SelectionLength++;
rtb.SelectedText = string.Empty;

I am bumping up the SelectionLength by one because, in my specific
case, I know that the text I will be removing will be followed by "\n"
and I want to remove it also.
 
Back
Top