Making specific text bold in a string in C# Windows Forms

11,958

You can do this with the help of FontStyle interface. Just add a button in your form and name it Bold and create a click event for that. You have to use RichTextBox for this, you cannot do this with TextBox. This code will convert the selected text to bold.

private void btnBold_Click(object sender, EventArgs e)
    {
        FontStyle style = tbMessage.SelectionFont.Style;
        if (tbMessage.SelectionFont.Bold)
        {
            style = style & ~FontStyle.Bold;
            btnBold.Font = new Font(btnBold.Font, FontStyle.Regular);
        }
        else
        {
            style = style | FontStyle.Bold;
            btnBold.Font = new Font(btnBold.Font, FontStyle.Bold);
        }
        tbMessage.SelectionFont = new Font(tbMessage.SelectionFont, style);
        tbMessage.Focus();

    }
Share:
11,958

Related videos on Youtube

Michael Naidis
Author by

Michael Naidis

Updated on June 04, 2022

Comments

  • Michael Naidis
    Michael Naidis about 2 years

    I want to make part of the text bold in a textbox, for example the textbox contains.

    "This is a text box"

    So it will be "This is a text box"

    How can I do it in C# Windows Forms?

    • Robert Langdon
      Robert Langdon almost 10 years
      So is it that only second word should be bold?
    • TheBetaProgrammer
      TheBetaProgrammer almost 10 years
      Try using html This '<b>is</b>' a text book
    • Michael Naidis
      Michael Naidis almost 10 years
      It's windows forms by the way, and not necessarily second, Robert - word of my choice.
    • user3613916
      user3613916 almost 10 years
      Is this a RichTextBox or just a normal TextBox?
  • Michael Naidis
    Michael Naidis almost 10 years
    What if I want just a word from the message?
  • pooja_baraskar
    pooja_baraskar almost 10 years
    select that word with the help of mouse and click on the bold button which has the event handler with code above. This will make the selected word Bold/Unbold. Just try this code once , you will understand.