4

I searched for this for A while but I couldn't find the answer, so I hope it's not a duplicate.

I have the following code:

this.Controls.Add(new Label { Location = new Point(10, 10), 
                              AutoSize = true, 
                              Name = "jobNumStatic",
                              Text = "Job Number:", 
                              Font = new Font(jobNumStatic.Font, FontStyle.Bold) });

I'm trying to change the font to bold. But that code gives the error, The name 'jobNumStatic' does not exist in the current context. Is there any way to make the font bold here?

I also tried:

jobNumStatic.Font = new Font(jobNumStatic.Font, FontStyle.Bold) });

After declaring the Label, and it gives me the same error.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
Joe Smith
  • 171
  • 1
  • 3
  • 14
  • Possible duplicate of [How do I set a textbox's text to bold at run time?](https://stackoverflow.com/questions/3089033/how-do-i-set-a-textboxs-text-to-bold-at-run-time) – n00dles May 28 '17 at 01:52

2 Answers2

16

To use a Label's default font as prototype just use the static Label.DefaultFont property:

this.Controls.Add(new Label { Location = new Point(10, 10), 
                          AutoSize = true, 
                          Name = "jobNumStatic",
                          Text = "Job Number:", 
                          Font = new Font(Label.DefaultFont, FontStyle.Bold) });

jobNumStatic is not a variable in your scope. You provide the string "jobNumStatic" at runtime for the Name property of the newly created Label, but that does not mean you magically have a variable with that name at compile-time.

If you need to access this Label later you may of course declare a member variable:

private Label jobNumStatic;

and assign the created instance to that variable:

jobNumStatic = new Label { Location = new Point(10, 10), 
                          AutoSize = true, 
                          Name = "jobNumStatic",
                          Text = "Job Number:", 
                          Font = new Font(Label.DefaultFont, FontStyle.Bold) });
this.Controls.Add(jobNumStatic);
René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

Simply use the code below:

Label1.Font = new Font(Font, Size, FontStyle.Bold);
Gnqz
  • 3,292
  • 3
  • 25
  • 35
  • I was able to use this, except I had to change it to this: Label1.Font = new Font(Label1.Font.FontFamily, Label1.Font.Size, FontStyle.Bold); – RPh_Coder Jan 08 '23 at 04:07