简体   繁体   中英

Changing a Label font to bold in code C#

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.

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);

Simply use the code below:

Label1.Font = new Font(Font, Size, FontStyle.Bold);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM