Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,
I have two text boxes.I want to change the selected text font to bold and italic.I have used two buttons namely bold and italic on which i have written code for bold and italic.but the problem is that if i change the font of selected text of one richtext box then it also changes the font of other richtext box text also.

How to solve it?

Code for bold button:
C#
if (rtbQuestion.SelectedText != null && rtbQuestion.SelectedText != "")
{
    rtbQuestion.SelectionFont = new Font(rtbQuestion.Font.FontFamily, this.Font.Size, FontStyle.Bold);
}
if (richTextBoxAnswerA.SelectedText != null && richTextBoxAnswerA.SelectedText != "")
{
    richTextBoxAnswerA.SelectionFont = new Font(richTextBoxAnswerA.Font.FontFamily, this.Font.Size, FontStyle.Bold);
}

Code for italic button:
C#
if (rtbQuestion.SelectedText != null && rtbQuestion.SelectedText != "")
{
    rtbQuestion.SelectionFont = new Font(rtbQuestion.Font.FontFamily, this.Font.Size, FontStyle.Italic);
}
if (richTextBoxAnswerA.SelectedText != null && richTextBoxAnswerA.SelectedText != "")
{
    richTextBoxAnswerA.SelectionFont = new Font(richTextBoxAnswerA.Font.FontFamily, this.Font.Size, FontStyle.Italic);
}
Posted
Updated 8-Oct-10 8:49am
v2

Well... Of course. The Bold or Italic FontStyle is applied to both RichTextBoxes because you wrote the code to change it for both in the same event handler.
Why did you expect the compiler to know which RichTextBox you want to be affected when you specified both of them??

By the way (not related to your question):
You should really write
C#
if (!string.IsNullOrEmpty(rtbQuestion.SelectedText))
{
    // ...
}

instead of
C#
if (rtbQuestion.SelectedText != null && rtbQuestion.SelectedText != "")
{
    // ...
}
 
Share this answer
 
v2
Your issue here is that when you click a button to change the font style the focus is taken from RichTextBox, which has the behaviour of hiding the selection when not in focus.

So when you make a selection in another RichTextBox and click a button your logic will apply to both boxes if they have a selection.

I would do one of the following:

1. Clear the selection of the boxes after the style modification has been made, probably the better idea as you may wish to change selections in multiple boxes.

2. Return the focus to the original box.


Hope this helps....
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900