How to apply font changes in run-time?

Joined
Dec 10, 2007
Messages
18
Location
Florida
Programming Experience
Beginner
My goal is to apply bold to a text when a certain event occurs. I have tried using
VB.NET:
me.TextBox.Font.Bold = True

But when I do that I get an error saying that this is a read only property. So I am stumped as to how to apply this change. Does anyone know? I tried searching google but, I only could find explanations dealing with richtextboxes.
 
Font objects are immutable, which means that once you create a Font you cannot change it. If you want to change the Font of your TextBox you have to create a new Font object and assign it to the Font property.

Changing the Style of a Font is quite common so a constructor exists intended for the purpose. What you need to do is apply the Bold style without affecting any other styles. You do this with bitwise operations on FontStyle values:
VB.NET:
Dim currentFont As Font = myControl.Font

'Apply the Bold style.
myControl.Font = New Font(currentFont, currentFont.Style Or FontStyle.Bold)

'Remove the Bold style.
myControl.Font = New Font(currentFont, currentFont.Style And Not FontStyle.Bold)

'Toggle the Bold style.
myControl.Font = New Font(currentFont, currentFont.Style Xor FontStyle.Bold)
 
Back
Top