0

I have a string builder where value is appending at runtime via placeholder. Once string builder has appended, it is assigned to a text box (not rich txt) to show up in UI.

I want part of the text to be bold.

sb.AppendFormat("Added {0} by {1}:\n{2}", DateTime.ToString(), userName, note);
txt.Text = sb.ToString();

Expected output:

Added 9/01/2016 8:47:19 PM by Vinoth: Testing Purpose

How can I achieve this? Is there anyway of looping over words with the : symbol until I want it to be bold?

thoniv
  • 79
  • 1
  • 1
  • 11
  • 7
    Text box does not support multiple font styles like that. – Matthew Watson Jan 29 '16 at 10:25
  • You can create a `TextBox` child class and override the `OnPaint` method and drawing the text manually (`e.Graphics.DrawString(...)`). Or you can use 2 `TextBox` (one bold and one normal). Or simpler, use a `RichTextBox`. – Bioukh Jan 29 '16 at 10:26
  • 3
    Just use a RichTextBox. It's not as hard as you think. – Matthew Watson Jan 29 '16 at 10:26
  • @MatthewWatson - how do you know he thinks it's hard? –  Jan 29 '16 at 10:27
  • Possible duplicate of [Formatting text in WinForm Label](http://stackoverflow.com/questions/11311/formatting-text-in-winform-label) – kjbartel Jan 29 '16 at 10:36
  • He is using TextBox not label, can not be said as duplicate. – Anil Jan 29 '16 at 10:37
  • subclassing TextBox is not recommended. Subclassing a Label to show different font styles is simple.. You do realize that your example contains not one but __three__ colons?? – TaW Jan 29 '16 at 19:34
  • @TaW yes i forget that point. I've asked client for RTB. Thanks for your comments – thoniv Jan 30 '16 at 08:12

1 Answers1

5

You will have to build up the text in sections.

Either as different TextBoxes/TextBlocks or as a single RichTextBox with separate Runs for the sections you want in a different style.

ChrisF
  • 134,786
  • 31
  • 255
  • 325