Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognizing sender button control in click event

I made a custom button that has a field named Data.

I add this button programatically during runtime to my winform and on adding I also define a click event for them. Well, Actually I only have one method and I subscribe the newly added buttons to this method.

But in the click event I want to access this Data field and show it as a message box, but it seems that my casting is not right:

    CustomButton_Click(object sender, EventArgs e)
    {
        Button button;
        if (sender is Button)
        {
            button = sender as Button;
        } 

        //How to access "Data" field in the sender button? 
        //button.Data  is not compiling!
    }

UPDATE:

I am sorry, I ment with "is not compiling" that .Data does not show up in intelisense...

like image 261
Saeid Yazdani Avatar asked Jul 08 '12 22:07

Saeid Yazdani


People also ask

Which event method is used for button control?

To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

What is Sender button C#?

as sender is the button , you are creating a object of the same button class and typecasting the button object and assigning to a local object, then accessing it's properties. This is useful if you have many objects using the same event handler.

Is button click an event?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.

What is the default event for a button control?

Default Events For example, default event for the button control is the Click event.


2 Answers

You need to cast to the type of your custom class that has the Data field.

Something like:

YourCustomButton button = sender as YourCustomButton;
like image 106
David Hall Avatar answered Sep 28 '22 18:09

David Hall


Assuming your custom button type is CustomButton, you should do this instead:

CustomButton_Click(object sender, EventArgs e){
  CustomButton button = sender as CustomButton;
  if (button != null){
      // Use your button here
  } 
}
like image 42
GETah Avatar answered Sep 28 '22 17:09

GETah