Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Change font of text in RichTextBox dynamically?

I am having some text in a "richTextBox" and a "comboBox" having names of some fonts. I want to change the font of text in "richTextBox" if a new font is selected from the "comboBox". I am using following code.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex == 1)
        richTextBox1.Font = new Font("Comic Sans MS", 14);
}

The problem is that if I select the font, the text does not change its font automatically, it only changes if I type some new text. I also tried richTextBox1.SelectionFont instead of richTextBox1.Font. I also added InputTextBox.Refresh(); after the above code to refresh the text box but in vein.

How I can change font of the text by just selecting from comboBox?

Update: I just figured out that above code is fine, the problem is that I was using wrong event call, used comboBox1_SelectedValueChanged() in place of comboBox1_SelectedIndexChanged() and it works fine now.

Tip: If you want to change font of entire TextBox use richTextBox1.Font, if you want to change font of selected text only use richTextBox1.SelectionFont.

like image 907
ePandit Avatar asked Jan 21 '23 02:01

ePandit


1 Answers

You could select all the text before changing SelectedFont option:

this.richTextBox1.SelectAll();
this.richTextBox1.SelectionFont = newFont;
like image 54
digEmAll Avatar answered Jan 30 '23 08:01

digEmAll