C# How to Make Selected Text Bold [.NET]

x BlueRobot

Administrator
Staff member
Joined
May 7, 2013
Posts
10,400
Evening everyone,

I'm attempted to make a simple parser which takes a string in BBCode format, removes the tags and then makes the text bold using the RichTextBox functionality. The text is made bold, however, a non-bold string is produced first and then the bold string.

Code:
private void parseButton_Click(object sender, EventArgs e)
        {
            foreach(String line in richTextBox1.Lines)
            {
                String[] subStrings = line.Split('-');

                foreach(String subString in subStrings)
                {
                    
                    if ((subString.StartsWith("['b]") && subString.EndsWith("['/b]")))
                    {
                        String noStartTag = "";
                        String noEndTag = "";

                        noStartTag = subString.Replace("['b]", "")[B];
                        [/B]noEndTag = noStartTag.Replace("[/'b]", "");
                        richTextBox2.SelectedText = noEndTag;
                        richTextBox2.SelectionFont = new Font(richTextBox2.Font, FontStyle.Bold);

                    }
                }

I believe the issue may lie with the fact that the Text property of the RichTextBox control is being populated first, and then a new string is being altered?
 
Why does the code split each line by '-'? I'm curious. Keep in mind if this gets expanded for further functionality, it wouldn't parse such bbcode as for instance like we have here. Aside from that, I did something like this a while back and the key is to change the font properties by creating a pair-map. I'm not sure how far you want to go with this, and I haven't pulled up an IDE yet, but is this only for bold tags so far?

Don't iterate over the lines either... What if I did this:
[CODE][NO-PARSE][b]line 1
line 2[/b][/NO-PARSE][/CODE]

;)
 
Last edited:
You can try something like this just for what you're trying to do:
Code:
[plain]string data = "[b]testing[b]12\r\n34[/b][/b] hello! [b]abcd[/b]";
richTextBox1.Text = data;

int n1 = 0;
int n2 = richTextBox1.Text.Length;

while ((n1 = richTextBox1.Text.IndexOf("[b]", n1)) != -1
    && (n2 = richTextBox1.Text.IndexOf("[/b]", n1)) != -1)
{
    richTextBox1.Select(n1 + 3, n2 - n1 - 3);
    using (var boldFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold))
        richTextBox1.SelectionFont = boldFont;

    n1 = n2;
}

richTextBox1.Rtf = richTextBox1.Rtf.Replace("[b]", string.Empty);
richTextBox1.Rtf = richTextBox1.Rtf.Replace("[/b]", string.Empty);[/plain]

Pretty minimal error checking.
 
Thanks Ace, that works perfectly!

I've decided to start this project, as a form of motivation to learn the .NET framework.
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top