How to add custom property and events to a control say textbox or button

11,284

Solution 1

You will have to create a custom control and then inherit the button class. Then create your custom properties and / or events.

Check this or this out from MSDN

Solution 2

You can inherit from the control you want and extend it however you wish. AFAIK none of the controls are sealed classes in winform. So you could add additional properties and events. Something like:

public class MyTextBox : System.Windows.Forms.TextBox {

public string MetaMessage {get;set;}

public event SomeCoolEventHandler CoolEvent;
public delegate SomeCoolEventHandler(object sender, CoolEventArgs args);
}

public class CoolEventArgs: EventArgs{

....
}
Share:
11,284
Shantanu Gupta
Author by

Shantanu Gupta

Debugging Minds... Looking For Learning Opportunities "Opportunities are Often The Beginning of Great Enterprise..." LinkedIn: https://www.linkedin.com/in/shantanufrom4387/

Updated on June 04, 2022

Comments

  • Shantanu Gupta
    Shantanu Gupta almost 2 years

    I want to add a custom property to a button in window form. Currently i am using following code to create my logic. but i want to create an enum value for a button control.

    btnPartyDetails.Text = "View";
    {}
    btnPartyDetails.Text = "Add";
    {}    
    btnPartyDetails.Text = "Delete";
    {}
    btnPartyDetails.Text = "Edit";
    {}
    

    I want to perform some action based on these values and i want to make a custom property for button so that i can use enum instead of using text match.

    btnPartyDetails.ActionType= ActionType.View;
    {}
    btnPartyDetails.ActionType= ActionType.Add;
    {}    
    btnPartyDetails.ActionType= ActionType.Delete;
    {}
    btnPartyDetails.ActionType= ActionType.Edit;
    {}
    

    I want to do something like this, where ActionType will be my enum.

    I also want to create custom event based on the value set. How can i do this ?