How do I tweak "sender" in an event?

Viewed 43

I have a code that may use randomLabel as a sender that fires an event. In this code, I attempt to tweak sender's Font properties but it seems to give a compile error. Is there any way to fix this?

    private void mainForm_Load(object sender, EventArgs e)
    {
        randomLabel.MouseEnter += RandomLabel_MouseEnter;
    }

    private void RandomLabel_MouseEnter(object sender, EventArgs e)
    {
        sender.Font = new Font(sender.Font, FontStyle.Bold);
    }
3 Answers

You can "tweak" the sender, but you have to cast it to the correct type so you can access its properties and methods.

private void RandomLabel_MouseEnter(object sender, EventArgs e)
{
    var sender2 = sender as Label;
    if (sender2 != null)
        sender2.Font = new Font(sender2.Font, FontStyle.Bold);
}

You need to cast sender to the appropriate control. E.g.

private void RandomLabel_MouseEnter(object sender, EventArgs e)
{
    Control control = sender as Control;
    if (sender != null)
    {
        control.Font = new Font(control.Font, FontStyle.Bold);
    }
    else
    {
        throw new InvalidArgumentException("sender");
    }
}

sender is of type object which does not have a Font property. You'd need to cast it to the appropriate type first

Assuming it is a Label..

((Label)sender).Font = new Font(((Label)sender).Font, FontStyle.Bold);

It is likely a good choice to make sure sender is actually the type you expect it is using either the is or as operators before hand though. Just in case

Related