1

Halo guys, i get a problem when I try to make program in C# winForm

I have make 3 button (btn_bold, btn_italic, btn_underline), when i code my btn_bold with

if (rTb_Isi.SelectionFont != null)
        {
            System.Drawing.Font currentFont = rTb_Isi.SelectionFont;
            System.Drawing.FontStyle newFontStyle;

            if (rTb_Isi.SelectionFont.Bold == true)
            {
                newFontStyle = FontStyle.Regular;
            }
            else
            {
                newFontStyle = FontStyle.Bold;
            }

            rTb_Isi.SelectionFont = new Font(
               currentFont.FontFamily,
               currentFont.Size,
               newFontStyle
            );
        }
    }

The problem is, when i click btn_bold, then italic text become bold, can't be bold and italic.

Do you know, how to make this code can work together like Ms. Word ?

I have try to change the code be

            if (rTb_Isi.SelectionFont != null)
        {
            System.Drawing.Font currentFont = rTb_Isi.SelectionFont;
            System.Drawing.FontStyle newFontStyle;

            if (rTb_Isi.SelectionFont.Bold == true)
            {
                newFontStyle = FontStyle.Regular;
            }
            else if (rTb_Isi.SelectionFont.Italic == true)
            {
                newFontStyle = FontStyle.Bold & FontStyle.Italic;
            }
            else
            {
                newFontStyle = FontStyle.Bold;
            }

            rTb_Isi.SelectionFont = new Font(
               currentFont.FontFamily,
               currentFont.Size,
               newFontStyle
            );
        }
    }

but it doesn't work :(

Hermanto
  • 23
  • 1
  • 4
  • 1
    Use | instead of & as you want to combine the bits – Mark PM Sep 27 '15 at 15:07
  • This may help you [http://stackoverflow.com/questions/26842232/richtextbox-font-style-button-for-bold-and-or-italic-how-to-code-so-more-than-o/41411015#41411015](http://stackoverflow.com/questions/26842232/richtextbox-font-style-button-for-bold-and-or-italic-how-to-code-so-more-than-o/41411015#41411015) – Monzur Dec 31 '16 at 19:33

1 Answers1

3

The FontStyle enum has the [Flags] attribute. That makes it very simple:

System.Drawing.FontStyle newFontStyle = FontStyle.Regular;
if (rTb_Isi.SelectionFont.Bold) newFontStyle |= FontStyle.Bold;
if (rTb_Isi.SelectionFont.Italic) newFontStyle |= FontStyle.Italic;
if (rTb_Isi.SelectionFont.Underline) newFontStyle |= FontStyle.Underline;
if (newFontStyle != rTb_Isi.SelectionFont.Style) {
    rTb_Isi.SelectionFont = new Font(currentFont.FontFamily, currentFont.Size, newFontStyle);
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536