Search code examples
c#winformsidentifier

How to tell which control accessed a method with multiple references?


I have 25 buttons that I've assigned into 1 method (snippet below). I want to be able to grab the clicked button's informations such as tags and name, and set the.Enabled property to false. I have this following code;

    int picksLeft = 5;
    int value = 100;
    string multiplier;
    string buttonName;

    private void btnPick_Click(object sender, EventArgs e) //My method with 25 references (buttons)
    {
        for (int i = 5; i > 0; i--)
        {
            if (lblPicks.Text == "Picks Left: " + i)
            {
                picksLeft = i - 1;
            }
        }
        lblPicks.Text = "Picks Left: " + picksLeft.ToString();
        //Get tag string, disable the button.
        //multiplier = buttonName.Tag;
        //Controls[buttonName].Enabled = false;
        //value -= value * Convert.ToDouble(multiplier);
    }

Solution

  • The sender object contains all the information, just cast it to button. As I remember it should look like this: button = sender as button; Then use it to refer to any of its properties.

    I hope it would help.

    Button btn;
    
     private void btnPick_Click(object sender, EventArgs e) //My method with 25 references (buttons)
     {
        for (int i = 5; i > 0; i--)
        {
            if (lblPicks.Text == "Picks Left: " + i)
            {
                picksLeft = i - 1;
            }
        }
        lblPicks.Text = "Picks Left: " + picksLeft.ToString();
        btn = sender as Button;
        btn.Enabled = false;
        multiplier = btn.Tag;
        value -= value * Convert.ToDouble(multiplier);
    }