简体   繁体   中英

How to make a text in the textbox both bold and italic?

I'm new to C# language. So I've created a form in Visual Studio and there are 3 checkboxes on it named Bold, Italic and Underlined. There is also a textbox. When I check the "Bold" checkbox, it makes my text bold and all the other checkboxes work like this but when I try to check 2 or all of them, only one of them works. Here's the code I wrote for making the text both bold and italic by checking the first and second checkbox and absolutely doesn't work:

if (checkBox1.Checked == true && checkBox2.Checked == true)
{
    textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
    textBox1.Font = new Font(textBox1.Font, FontStyle.Italic);
}

I also have a combobox for font size and it works well but when I check the "Bold" checkbox and then change the font size, it goes back to regular font style and doesn't stay bold. What should I do?

You're setting the font twice rather than combining the values. If you look at the definition of FontStyle you will see that it is a bitfield (it has the flags attribute). Just OR the values. (Note that we use the bitwise OR rather than the Boolean OR)

{
    textBox1.Font = new Font(textBox1.Font, FontStyle.Bold | FontStyle.Italic);
}

It would, however, be better to structure your code slightly differently:

FontStyle style;
if (checkBox1.Checked)
{
    style = style | FontStyle.Bold;
}
if (checkBox2.Checked)
{
    style = style | FontStyle.Italic;
}

textBox1.Font = new Font(style);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM