7

C# doesn't like the following code:

private void btnSizeRandom_Click(object sender, EventArgs e)
{
  btnSizeRandom.Font.Bold = true;
  btnother.Font.Bold = false;
}

Is there a way to do this programatically?

Jim
  • 3,425
  • 9
  • 32
  • 49

2 Answers2

18

Instances of Font are immutable. You need to construct a new Font and assign it to the Font property. The Font class has various constructors for this purpose; they copy another instance and change the style in the process.

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
  • 11
    +1 And just to round out the great answer: btnSizeRandom.Font = new Font(btnSizeRandom.Font, FontStyle.Bold); – SwDevMan81 Jun 30 '10 at 20:55
  • @SwDevMan81 Additionally, you need: new system.Drawing.Font(btnSizeRandom.Font, FontStyle.Regular); – Recipe Jul 26 '13 at 08:46
11
    private static Font ChangeBoldStyle(Font org, bool bold) {
        FontStyle style = org.Style;
        if (bold) style |= FontStyle.Bold;
        else style &= ~FontStyle.Bold;
        return new Font(org, style);
    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536