I have an event handler for a Textbox as well as for a RichTextBox. The code is identical, but
In handler #1 i do:
RichTextBox tb = (RichTextBox)sender
In handler #2 accordingly:
TextBox tb = (TextBox)sender
Doing so i can fully manipulate the sending control. What i want to know is how can i cast the sending object to Textbox or RichTextbox according to its type using
sender.GetType().Name
and then create the control at runtime and work with it. That way i only need one event handler function: less code, less errors, easier to maintain and DRY :-)
sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
The C# Object sender is one of the argument, and it's a parameter for creating the reference of the object which has been raised for the events that are used for to respond the handler to mapping the correct object but in case of static parameters or events, the value will be null with the help of EventArgs class we ...
Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event. Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx. Example: protected void btn_Click (object sender, EventArgs e){ Button btn = sender as Button; btn.Text = "clicked!"; }
You never have to cast. I used to think the same way when I started, this 'pattern' is incorrect, and not really logical.
Your best bet is to use something like:
if (sender is TextBox) { TextBox tb = (TextBox)sender; } else if (sender is RichTextBox) { RichTextBox rtb = (RichTextBox)sender; } else { // etc }
I know this is a very old post but in Framework 4 you can cast the sender as a Control:
Control cntrl = (Control)sender; cntrl.Text = "This is a " + sender.GetType().ToString();
Note you are only able to reference controls that all of the different controls have in common (ie Text).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With