Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to change font of a label

A form with a label and a button 'Options'. By clicking the button a new form opens with 2 radio buttons 'Font1' and 'Font2', and two buttons 'Apply' and 'Cancel'. Upon selecting one of the radio buttons and clicking 'Apply' will make the label on the first form change the font face. The problem is how to change the font as in from say Tahoma to Arial or to any other font face of the label.

Options form code for apply button, which if was clicked will return dialogresult.ok == true and change the font of the label on the first form:

private void btnApply_Click(object sender, EventArgs e)
{
    if (radioFont1.Checked)
    {
        mainForm.lblName.Font.Name = "Arial"; 'wrong attempt 
    }
    this.DialogResult = DialogResult.OK;
}

Declaration of the label on first form so that it is visible to second form:

public static Label lblName = new Label();

...

private void mainForm_Load(object sender, EventArgs e)
{
    lblName = lblBarName;
}
like image 868
TheEnd Avatar asked Feb 08 '11 22:02

TheEnd


1 Answers

Font.Name, Font.XYZProperty, etc are readonly as Font is an immutable object, so you need to specify a new Font object to replace it:

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Check the constructor of the Font class for further options.

like image 187
djdd87 Avatar answered Oct 24 '22 09:10

djdd87