Reputation: 1215
I have a RichTextBox. I want change fontStyle of selected text without change FontFamily.
I use this code
RTBMain.SelectionFont = new Font(RTBMain.SelectionFont, FontStyle.Bold);
It is change fontstyle, but my problem is :
When i select a text with change fontfamily, i get error
Object reference not set to an instance of an object.
beacuse
RTBMain.SelectionFont=null
For example :
My text is "I have a student "
FontFamily for "a" is "Tahoma"
FontFamily for "student" is "Tango"
Then i select "a student" : FontFamily for this is null.
But when i select "a" or "student" : font family not is null.
Upvotes: 4
Views: 8731
Reputation: 9888
For example:
richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);
richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Red;
You need to select the text you want to change format, first.
And SelectionFont
cannot be two fonts at the same time.
Upvotes: 1
Reputation: 6079
if(RTBMain.SelectionFont != null)
{
RTBMain.SelectionFont = new Font(RTBMain.SelectionFont, FontStyle.Bold);
}
or
if (RTBMain.SelectionLength > 0)
{
RTBMain.SelectionFont = new Font(RTBMain.SelectionFont, FontStyle.Bold);
}
private void ToggleBold()
{
if (richTextBox1.SelectionFont != null)
{
System.Drawing.Font currentFont = richTextBox1.SelectionFont;
System.Drawing.FontStyle newFontStyle;
if (richTextBox1.SelectionFont.Bold == true)
{
newFontStyle = FontStyle.Regular;
}
else
{
newFontStyle = FontStyle.Bold;
}
richTextBox1.SelectionFont = new Font(
currentFont.FontFamily,
currentFont.Size,
newFontStyle
);
}
}
Upvotes: 4