How do I set a textbox's text to bold at run time?

前端 未结 5 1427
野的像风
野的像风 2020-12-08 12:44

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 characteristi

5条回答
  •  余生分开走
    2020-12-08 13:16

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

提交回复
热议问题