Gap between Text and underline of label control

Shaifali jain 420 Reputation points
2023-09-22T08:49:58.82+00:00

Hi ,

is it possible to increase the gap between the text and underline in a label control .
for example , below is a label with underline in vs
User's image

and this is what i have to
User's image

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,738 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,504 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brian Zarb 1,660 Reputation points
    2023-09-22T09:11:53.24+00:00

    a common workaround is to create a custom control by subclassing the Label control and overriding its OnPaint method to draw the text and the underline manually, thereby giving you control over the gap. Here's a simple example of how you could do this:

    using System;
    using System.Drawing;  
    using System.Windows.Forms;  
    
    public class UnderlinedLabel : Label{      
    	protected override void OnPaint(PaintEventArgs e){          
    		base.OnPaint(e);          
    		if (this.Text.Length > 0){              
    			SizeF textSize = e.Graphics.MeasureString(this.Text, this.Font);              
    			float gap = 3; // adjust the gap as needed              
    			float underlineY = textSize.Height + gap;              
    			e.Graphics.DrawLine(Pens.Black, 0, underlineY, textSize.Width, underlineY);          
    		}      
    	}  
    }
    
    

    In this example, underlineY determines the Y-coordinate of the underline. By adjusting the gap value, you can control the distance between the text and the underline.

    Once you have this custom control, you can use it in your form like any other control:

    UnderlinedLabel underlinedLabel = new UnderlinedLabel();
    underlinedLabel.Text = "Underlined Text";
    underlinedLabel.Location = new Point(50, 50);
    this.Controls.Add(underlinedLabel);
    

    This should allow you to have a label with a customizable gap between the text and the underline in your Windows Forms application.


0 additional answers

Sort by: Most helpful