Formatting in RichTextBox

I am having a trouble in RichTextBox Control in Windows application,I have three buttons bold,underlined and Italics for the RichTextBox.I am selecting a sentence which is partially regular and partially bold . After selecting that sentence , i am trying to convert the selected sentence into italics , the below code is giving me the expected output but it searching for each and every character. Tell me any other way to solve this issue ...

Steps to Recreate :
1) Add two paragraphs inside the RichTextBox.
2) For the first paragraph apply bold style.
3) For the second paragraph apply regular style.
4) Now select two paragraphs and apply underline style.
5) you could see , two paragraphs converted into regular style with text underlined .

private void SetFontStyle(RichTextBox rtb, FontStyle style)
int selectionStart = rtb.SelectionStart;
int selectionLength = rtb.SelectionLength;
int selectionEnd = selectionStart + selectionLength;
for( int x = selectionStart; x < selectionEnd; ++x )
// Set temporary selection
rtb.Select(x, 1);
// Toggle font style of the selection
rtb.SelectionFont = new Font(rtb.SelectionFont, rtb.SelectionFont.Style ^ style);
// Restore the original selection
rtb.Select(selectionStart, selectionLength);

Thanks and Regards,

Faizal Ahmed.H
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!