Richtextbox specific line in bold

Asked

Viewed 313 times

0

I have a Richtextbox where I need to leave the lines of positions [0] and [6] in bold.

I have the following code:

 rtbDadosAdicionais.Select(0, rtbDadosAdicionais.Lines[0].Length);
 rtbDadosAdicionais.SelectionFont = new Font("", 15, FontStyle.Bold);
 //Para deixar a linha [0] em negrito

 rtbDadosAdicionais.Select(0, rtbDadosAdicionais.Lines[6].Length);
 rtbDadosAdicionais.SelectionFont = new Font("", 15, FontStyle.Bold);
 //Para deixar a linha [6] em negrito

But the line [6] is not staying. Thank you.

1 answer

1


I took the following method from within the code of RichBoxExtended, I didn’t make it, but it might help you:

    public void ChangeFontStyle(FontStyle style, bool add)
    {
        //This method should handle cases that occur when multiple fonts/styles are selected
        // Parameters:-
        //  style - eg FontStyle.Bold
        //  add - IF true then add else remove

        // throw error if style isn't: bold, italic, strikeout or underline
        if (   style != FontStyle.Bold
            && style != FontStyle.Italic
            && style != FontStyle.Strikeout
            && style != FontStyle.Underline)
                throw new  System.InvalidProgramException("Invalid style parameter to ChangeFontStyle");

        int rtb1start = rtb1.SelectionStart;                
        int len = rtb1.SelectionLength; 
        int rtbTempStart = 0;           

        //if len <= 1 and there is a selection font then just handle and return
        if(len <= 1 && rtb1.SelectionFont != null)
        {
            //add or remove style 
            if (add)
                rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style | style);
            else
                rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style & ~style);

            return;
        }

        // Step through the selected text one char at a time    
        rtbTemp.Rtf = rtb1.SelectedRtf;
        for(int i = 0; i < len; ++i) 
        { 
            rtbTemp.Select(rtbTempStart + i, 1); 

            //add or remove style 
            if (add)
                rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style | style);
            else
                rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style & ~style);
        }

        // Replace & reselect
        rtbTemp.Select(rtbTempStart,len);
        rtb1.SelectedRtf = rtbTemp.SelectedRtf;
        rtb1.Select(rtb1start,len);
        return;
    }

rtbTemp is a RichTextBox auxiliary, and rtb1 is the RichTextBox leading.

  • 1

    It helped a lot, I found this method very interesting. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.