different colors on Label control

  • Thread starter Thread starter Glenn Lerner
  • Start date Start date
G

Glenn Lerner

Hi,

Is it possible to have different foreground colors on a single lable? I
don't want to create multiple lable controls because each item that I
want in different color may change length during run time.

Example:
Qty: 1,000 Price: $2,000.00

I may want Qty and Price in black and the numbers in blue.

Thanks,
Glenn
 
Hi Glenn,

It is possible, but I think you may have to make your own control,
possibly inherited from Label.
It is simple enough, just override the Paint event (or handle the Paint
event in a label control) and use
the graphics object you get passed.

This sample demonstrates how to make a two color label coloring two
separate words in the same label using the label's paint event:

private void label1_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{
string[] temp = label1.Text.Split(new char[]{' '});
float startX = e.Graphics.MeasureString(temp[0] + " ", label1.Font).Width;
float startX2 = startX + e.Graphics.MeasureString(temp[1],
label1.Font).Width;

e.Graphics.FillRectangle(Brushes.LightGreen, 0, 0, startX, label1.Height);
e.Graphics.FillRectangle(Brushes.LightBlue, startX, 0, startX2-startX,
label1.Height);
e.Graphics.DrawString(label1.Text, label1.Font, Brushes.Black, 0, 0);
// you might want to adjust the positions
}

But to make it simpler than using separate labels I would make a new
control.

Happy coding!
Morten
 
Morten said:
Hi Glenn,

It is possible, but I think you may have to make your own control,
possibly inherited from Label.
It is simple enough, just override the Paint event (or handle the Paint
event in a label control) and use
the graphics object you get passed.

This sample demonstrates how to make a two color label coloring two
separate words in the same label using the label's paint event:

private void label1_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{
string[] temp = label1.Text.Split(new char[]{' '});
float startX = e.Graphics.MeasureString(temp[0] + " ",
label1.Font).Width;
float startX2 = startX + e.Graphics.MeasureString(temp[1],
label1.Font).Width;

e.Graphics.FillRectangle(Brushes.LightGreen, 0, 0, startX,
label1.Height);
e.Graphics.FillRectangle(Brushes.LightBlue, startX, 0,
startX2-startX, label1.Height);
e.Graphics.DrawString(label1.Text, label1.Font, Brushes.Black, 0, 0);
// you might want to adjust the positions
}

But to make it simpler than using separate labels I would make a new
control.

Happy coding!
Morten

This is what I needed! Thanks.
 
Back
Top