Home > Enterprise >  How to get an attribute from an unspecified object?
How to get an attribute from an unspecified object?

Time:12-10

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");
    }

CodePudding user response:

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");
 }
  • Related