views:

51

answers:

2

I'm using Windows forms and I have a textbox which I would occassionally like to make the text bold if it is a certain value.

How do I change the font characteristics at run time?

I see that there is a property called textbox1.Font.Bold but this is a Get only property.

+4  A: 

The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);

And then back again:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
chibacity
thanks! wow, that was much easier than i imagined. So I guess that means a font is like a string, once you create it, you can't change it. you can only declare a new instance of it.
RoboShop
Yes it appears to behave like string in terms of not being able to change its state once created i.e. it is [immutable](http://en.wikipedia.org/wiki/Immutable_object). However, although there are MSDN articles that refer to Font being immutable, the actual reference for Font itself does not state this.
chibacity
+1  A: 

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterEvents();
    }

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}
Robert Hui
thanks, that's exactly what i did. :)
RoboShop