Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get an attribute from an unspecified object?

My program dynamically creates a number of buttons at runtime. All of them get attached to an EventHandler, which links to the same method. How to know which button was pressed when the method executes? I tried using sender.Name, because object sender is a Button at runtime, but it doesn’t compile.

    List<Button> buttons = new List<Button>();

    private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 1; i < 3; i++)
        {
            buttons.Add(new Button() { Name = "btn" + i });
            buttons.Last().Click += new EventHandler(btn_Click);
        }            
    }
    public void btn_Click(object sender, EventArgs e)
    {
        MessageBox.Show(sender.Name + " is clicked");
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are on the right track.

The problem you have is that in btn_Click the sender is a generic object, so the compiler doesn’t know what type it is, so you need to tell it by casting.

 public void btn_Click(object sender, EventArgs e)
 {    
     Button senderButton = (Button)sender;
     MessageBox.Show(senderButton.Name + " is clicked");
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading