Alexandru Pupsa
Alexandru Pupsa

Reputation: 1878

How do I refer to the control from one of its events?

Is there an easier way of getting the 'panelDown' object, in order to have the same code in all controls?


    private void panelDown_MouseHover(object sender, EventArgs e)
    {
        **panelDown**.BorderStyle = BorderStyle.FixedSingle;
    }

Upvotes: 0

Views: 105

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500535

Rather than using as in the way that Nico has suggested, I'd cast:

private void panelDown_MouseHover(object sender, EventArgs e)
{
    var panel = (Panel) sender;
    panel.BorderStyle = BorderStyle.FixedSingle;
}

When you're converting unconditionally, using a cast is preferrable as if you've got the wrong type, the exception thrown (ClassCastException) is much clearer than getting a NullReferenceException when you use the result of an as with the wrong input.

(You don't have to use two statements here, of course - I just find it clearer.)

Use as when it's valid for the input to be of a different type, and you'll conditionally take action if it's the right type.

If you're wiring up the event handler manually, you can capture the relevant variable instead using a lambda expression, of course:

foo.MouseHover += (sender, args) => foo.BorderStyle = BorderStyle.FixedSingle;

Or:

foo.MouseHover += delegate { foo.BorderStyle = BorderStyle.FixedSingle };

Upvotes: 7

Ria
Ria

Reputation: 10347

cast sender to your Control (may be Panel).

((Panel) sender).BorderStyle = BorderStyle.FixedSingle;

Upvotes: 1

Nico Schertler
Nico Schertler

Reputation: 32597

private void panelDown_MouseHover(object sender, EventArgs e)
{
    (sender as Panel).BorderStyle = BorderStyle.FixedSingle;
}

Upvotes: 1

Related Questions