38

Is there any way to make a part of a label.text to be bold?

label.text = "asd" + string;

Would like the string portion to be bold.

Is possible, how can this be done?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Phil
  • 507
  • 2
  • 5
  • 7

12 Answers12

32

The following class illustrates how to do it by overriding OnPaint() in the Label class of WinForms. You can refine it. But what I did was to use the pipe character (|) in a string to tell the OnPaint() method to print text before the | as bold and after it as normal text.

class LabelX : Label
{
    protected override void OnPaint(PaintEventArgs e) {
        Point drawPoint = new Point(0, 0);

        string[] ary = Text.Split(new char[] { '|' });
        if (ary.Length == 2) {
            Font normalFont = this.Font;

            Font boldFont = new Font(normalFont, FontStyle.Bold);

            Size boldSize = TextRenderer.MeasureText(ary[0], boldFont);
            Size normalSize = TextRenderer.MeasureText(ary[1], normalFont);

            Rectangle boldRect = new Rectangle(drawPoint, boldSize);
            Rectangle normalRect = new Rectangle(
                boldRect.Right, boldRect.Top, normalSize.Width, normalSize.Height);

            TextRenderer.DrawText(e.Graphics, ary[0], boldFont, boldRect, ForeColor);
            TextRenderer.DrawText(e.Graphics, ary[1], normalFont, normalRect, ForeColor);
        }
        else {

            TextRenderer.DrawText(e.Graphics, Text, Font, drawPoint, ForeColor);                
        }
    }
}

Here's how to use it:

LabelX x = new LabelX();
Controls.Add(x);
x.Dock = DockStyle.Top;
x.Text = "Hello | World";       

Hello will be printed in bold and world in normal.

LeopardSkinPillBoxHat
  • 28,915
  • 15
  • 75
  • 111
particle
  • 3,280
  • 4
  • 27
  • 39
  • Vertical alignment is broken with this code, if the height of the label is more than one line and you want to center it vertically in the middle. (like Middle Left for example) – Tanuki May 01 '23 at 21:27
21

WinForms doesn't allow you to do that.

Jay Brown
  • 139
  • 2
  • 13
iburlakov
  • 4,164
  • 7
  • 38
  • 40
21

WebForms

Use Literal control, and add a <b> tag around the part of the text you want:

_myLiteral.Text = "Hello <b>big</b> world";

Winforms

Two options:

  1. Put two labels side by side (far easier)
  2. Subclass Label and do your own custom drawing in the OnPaint() method.

The second choice has been answered already.

Community
  • 1
  • 1
Chris S
  • 64,770
  • 52
  • 221
  • 239
8

This is an elaboration on Simon's suggestion of replacing the Label control with a readonly RichTextBox control.

  1. Replace the Label control with a RichTextBox control, same location and size. In following notes the name of the control is rtbResults.

  2. Make it readonly: rtbResults.ReadOnly = True;

  3. No borders: rtbResults.BorderStyle = BorderStyle.None;

  4. Instead of assigning the string to be displayed to Label.Text you assign it to RichTextBox.Rtf, and apply some simple RTF formatting.

The following code is a sample - it displays words generated by a Scrabble cheater program where the high-value letters are in bold.

  /// <summary>
  /// Method to display the results in the RichTextBox, prefixed with "Results: " and with the 
  /// letters J, Q, X and Z in bold type.
  /// </summary>
  private void DisplayResults(string resultString)
  {
     resultString = MakeSubStringBold(resultString, "J");
     resultString = MakeSubStringBold(resultString, "Q");
     resultString = MakeSubStringBold(resultString, "X");
     resultString = MakeSubStringBold(resultString, "Z");

     rtbResults.Rtf = @"{\rtf1\ansi " + "Results: " + resultString + "}";
  }


  /// <summary>
  /// Method to apply RTF-style formatting to make all occurrences of a substring in a string 
  /// bold. 
  /// </summary>
  private static string MakeSubStringBold(string theString, string subString)
  {
     return theString.Replace(subString, @"\b " + subString + @"\b0 ");
  }
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
RenniePet
  • 11,420
  • 7
  • 80
  • 106
3

Does it need to be a Label control, or do you just need to put text in a particular place? If the former, you'll need to do custom painting as other people have noted. If not, you could use a readonly RichTextBox instead.

Simon
  • 25,468
  • 44
  • 152
  • 266
2

The easy way to do what you want is just to add two labels. In this way you could make one bold, and it will look ok with a proper positioning.

The normal way would be to create a control that has two or more labels and you could set the properties on each one of them. Also this has the advantage that is reusable.

Adrian Fâciu
  • 12,414
  • 3
  • 53
  • 68
1

In WinForms override Label.OnPaint() method and draw the text your self.

Tadas Šukys
  • 4,140
  • 4
  • 27
  • 32
  • however, if you set `label.text = "asd" + string;` I don't know how you will separate **bold** from regular. – serhio Jan 14 '10 at 10:21
1

In ASP.NET you could do:

label.Text = string.Format("asd <span style='font-weight: bold;'>{0}</span>", string);

But like everyone else says, depends on what you're using.

Town
  • 14,706
  • 3
  • 48
  • 72
0

It depends on how pragmatic you are. Something that sounds overkill, but could work, is to use a web browser control in your form, and feed into it HTML markup. As I said overkill for a label, but if you have more than one line of text you need to format, it might be an option. – H. Abraham Chavez just now edit

H. Abraham Chavez
  • 828
  • 2
  • 8
  • 20
0

Use Infragistics' UltraLabel control - it supports html formatting. There are probably other third party solutions too.

vezenkov
  • 4,009
  • 1
  • 26
  • 27
0

I've built a UserControl that holds a TransparentRichTextBox allowing you to format portions of text by using the RTF syntax.

Nothing special and the syntax is quite easy to understand. Check it out here.

Community
  • 1
  • 1
Martin Braun
  • 10,906
  • 9
  • 64
  • 105
0

VB.NET Solution

I took @affan's answer answer of extending the Label Class and overriding the OnPaint method.

I translated his solution into VB and made a few changes to overcome some issues I was having with padding. My version also makes the text to the right of the pipe character | bold instead of the left.

Example: Example

Imports System.Windows.Forms
Imports System.Drawing

' Add some custom functionality to the standard Label Class
Public Class CustomLabel
    Inherits Label

    ' Allow bold font for right half of a label 
    ' indicated by the placement of a pipe char '|' in the string (ex. "Hello | World" will make bold 'World'
    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        Dim drawPoint As Point = New Point(0, 0)
        Dim boldDelimiter As Char = "|"c

        Dim ary() As String = Me.Text.Split(boldDelimiter)

        If ary.Length = 2 Then
            Dim normalFont As Font = Me.Font
            Dim boldFont As Font = New Font(normalFont, FontStyle.Bold)

            ' Set TextFormatFlags to no padding so strings are drawn together.
            Dim flags As TextFormatFlags = TextFormatFlags.NoPadding

            ' Declare a proposed size with dimensions set to the maximum integer value. https://msdn.microsoft.com/en-us/library/8wafk2kt(v=vs.110).aspx
            Dim proposedSize As Size = New Size(Integer.MaxValue, Integer.MaxValue)

            Dim normalSize As Size = TextRenderer.MeasureText(e.Graphics, ary(0), normalFont, proposedSize, flags)
            Dim boldSize As Size = TextRenderer.MeasureText(e.Graphics, ary(1), boldFont, proposedSize, flags)

            Dim normalRect As Rectangle = New Rectangle(drawPoint, normalSize)
            Dim boldRect As Rectangle = New Rectangle(normalRect.Right, normalRect.Top, boldSize.Width, boldSize.Height)

            

            TextRenderer.DrawText(e.Graphics, ary(0), normalFont, normalRect, Me.ForeColor, flags)
            TextRenderer.DrawText(e.Graphics, ary(1), boldFont, boldRect, Me.ForeColor, flags)

        Else
            ' Default to base class method
            MyBase.OnPaint(e)
        End If

    End Sub


End Class
Community
  • 1
  • 1
Chris
  • 2,166
  • 1
  • 24
  • 37