Changing button's text to bold via code in C#

G

Guest

I am trying to change the text on a button face to bold and/or to regular via
code using C#. I cannot seem to get it to work. Could someone offer me some
examples?

Here is my code:

public void UnboldAll()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
(ctrl as Button).Font = new Font((ctrl as Button).Font,(ctrl as
Button).Font.Style | FontStyle.Regular);
}
}

I get the following compile error:

frmDatePicker.cs(88): No overload for method 'Font' takes '2' arguments

Thanks in advance,
Noble
 
G

Guest

Change it to:

(ctrl as Button).Font = new Font((ctrl as Button).Font.Name, (ctrl as
Button).Font.Size, (ctrl as Button).Font.Style | FontStyle.Regular);
 
S

Stephen Souness

Looks like the Compact Framework doesn't support a Font constructor with
those arguments.

Try specifying the font size as well.

Something along the lines of:

(ctrl as Button).Font = new Font((ctrl as Button).Font, (ctrl as
Button).Font.Size, (ctrl as Button).Font.Style | FontStyle.Regular);
 
A

Alex Feinman [MVP]

Two things:
First, Bold = 2 and Regular = 0 so you need to invert bold to get rid of it
Second, you can boldly (pun intended) do away with typecasts:

To bold:
ctrl.Font = new Font(ctrl.Font.Name, ctrl.Font.Size, ctrl.Font.Style |
FontStyle.Bold);
Back to regular:
ctrl.Font = new Font(ctrl.Font.Name, ctrl.Font.Size, ctrl.Font.Style &
~FontStyle.Bold);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top