Can I change the font color on a portion of a string?
Solution 1
You cannot change the "color" of a string, just like you can't change the color of a number or a list or any other data type that simply stores values.
What you need to do is to modify the visual representation of that data, in this case the Label
control. Anything deriving from Control
has an available ForeColor
and BackColor
property.
An easy way to do what you need in WinForms is to group several Labels next to each other in a Panel
, change colors on each as desired, and then manipulate the Panel
as a single entity as necessary.
Solution 2
You should create several labels with different colors to create that. You can use a panel if your goal is to hide/show the labels for easier manipulation.
Solution 3
The Label
control only supports one ForeColor
at a time. If you need to handle more than one colour simultaneously, you could set up a FlowLayoutPanel
that flows horizontally, then include multiple Label
s in it that are coloured as you choose. It isn't the prettiest solution on earth programmatically speaking, but I believe it should work for you.
I say use a FlowLayoutPanel
and not a Panel
because this will allow you to use variable-length strings without worrying about positioning.
In essence, do something like this. The Control creation, of course, would generally occur in the designer. But you see how it could work.
FlowLayoutPanel flp = new FlowLayoutPanel();
Label lblA = new Label();
lblA.Text = "Hi ";
flp.Controls.Add(lblA);
Label lblB = new Label();
lblB.Text = m_senior;
lblB.ForeColor = Color.Red;
flp.Controls.Add(lblB);
Label lblC = new Label();
lblC.Text = " and "; // The spaces for this and "Hi " may or may not be necessary. They are in theory, but it's mostly dependent on the margins of the Labels. Just check which looks best.
flp.Controls.Add(lblC);
Label lblD = new Label();
lblD.Text = m_pwd;
lblD.ForeColor = Color.Red;
flp.Controls.Add(lblD);
Comments
-
NatsuDragneel almost 2 years
Can I change the color on the portion of the following string represented by
m_pwd
andm_senior
?string m_pwd = "PWD"; string m_senior = "Senior"; lblMarquee.Text = "Hi" + m_senior + "and" + m_pwd;