-1

I was looking to simplify the following action: Click on a panel, and the panel changes its color to green, and if it is green, change it back to gray. I was wondering how you would write the controls into the method as an argument so that it would work for any control without having to duplicate the event method.

Normally: Panel Click event

panel_Click ()
   //some if statement
   panel1.BackColor = green
   panel1.BackColor = gray

then repeat per control. Instead of this, I would create a central method that all of the controls are subscribed to, that read the name of the panel like:

genericpanel_Click(){
  ChangeColor(thisPanelname);
}

and then that would make use of the argument/parameter:

public void ChangeColor(panel? Mypanel) {
  //some if...
  Mypanel.BackColor = Green
  Mypanel.BackColor = Gray
}

What's the accurate equivalent of this pseudo code into a working one?

Edit: Okay, yes, I can see now that it's a duplicate, no need to downvote further. I just didn't know what to search for specifically. Anyways, I've found the answer at this point.

1
  • 1
    Include the object sender parameter in the event method, cast it to panel and then change its colors? Commented Apr 20, 2017 at 7:33

2 Answers 2

1

All events of a control provide its source as the first argument. You just have to cast it to the right type:

void panel_Click(object sender, EventArgs e) {
    Panel myPanel = (Panel)sender;
    ChangeColor(myPanel);
}

All definitions for event handler delegates provide the sender, for example:

public delegate void EventHandler(object sender, EventArgs e);
public delegate void EventHandler<T>(object sender, T e);

In case you define your own events, just use those delegate types and pass the source of the event as the first argument.

Sign up to request clarification or add additional context in comments.

Comments

1

You can subscribe all panels to this method:

private void panel_Click(object sender, EventArgs e)
{
    Panel clickedPanel = sender as Panel;
    if ( clickedPanel != null )
    {
        if ( clickedPanel.BackColor == Color.Blue )
        {
            clickedPanel.BackColor = Color.Red;
        }
        else 
        {
            clickedPanel.BackColor = Color.Blue;
        }
    }
}

If you only subscribe panels to this even the first check wouldn't be needed, but to be safe its there.

This method takes the sender (the panel that activated the event) and check's its background color. If color A set to Color B -> else Color A

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.