Search code examples
c#winformscustom-controls

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...


Solution

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

    Something like:

    YourCustomButton button = sender as YourCustomButton;