0

I apply a FontStyle Bold on a text selected with a button but I can't go back to the default value when I click on it again I would like that when I click the first time, the FontStyle Bold is applied and when I click again, the FontStyle Regular is applied. Could someone please help me?

 private void button3_Click(object sender, EventArgs e)
    {
      System.Drawing.Font bold = richTextBox1.SelectionFont;
        System.Drawing.FontStyle noBold;

       if (richTextBox1.SelectionFont.Bold == true)
       {
            noBold = FontStyle.Regular;
            
       }
        else
        {
            noBold = FontStyle.Bold;
        }

        richTextBox1.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, noBold);

    }
Smoky
  • 1
  • 1
  • 1
    You are not "changing" the font at all, but creating a **new** font each time. Create a Bold and NonBold font object and reuse it as needed. As for your problem - your code is not switching simply on the button click but it also checks if there is some selected text. Both the condition and the event need to happen – Ňɏssa Pøngjǣrdenlarp Apr 07 '22 at 01:03
  • Thanks for your answer Ňɏssa Pøngjǣrdenlarp, I have modified and created 2 objects but I can't get the noBold value when I click a second time on the button.I modified the code as above but I am still in my same situation... – Smoky Apr 07 '22 at 13:23
  • I finally understood and succeeded, many thanks @Ňɏssa Pøngjǣrdenlarp ;) I post my new code if it helps – Smoky Apr 07 '22 at 14:36

1 Answers1

0

Your logic is faulty. You're checking if there is selected text and if there is, you make it bold, otherwise you make it not bold, except there is no selected text so nobold has no effect.

You want to do something more along the following lines (Note that this example code is self-contained. You should initialize your font objects elsewhere.):

Font bold = null;
Font noBold = null;
private void button3_Click(object sender, EventArgs e)
{
  if(richTextBox1.SelectedText == null)
    return;
  if (bold == null)
    bold = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, FontStyle.Bold);
  if (nobold == null)
    noBold = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, FontStyle.Regular);


  if ( (richTextBox1.SelectionFont == null) || (richTextBox1.SelectionFont == noBold) )
  {
    richTextBox1.SelectionFont = bold;
  }
  else
  {
    richTextBox1.SelectionFont = noBold;
  }

}
EddieLotter
  • 324
  • 3
  • 8
  • Thank you ;) indeed my logic was not good and when I see your code, I think I was close to that on my last example, I will analyze it well to understand the difference. Thanks @EddieLotter. – Smoky Apr 07 '22 at 14:45
  • @Smoky, you're welcome. Let me know if you have any questions. – EddieLotter Apr 07 '22 at 22:48