Hermanto
Hermanto

Reputation: 23

How to set bold, italic, underline together for C# Winform

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 :(

Upvotes: 1

Views: 8222

Answers (1)

Hans Passant
Hans Passant

Reputation: 941635

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);
}

Upvotes: 3

Related Questions