Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast sender object in event handler using GetType().Name

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 :-)

like image 667
tfl Avatar asked Mar 11 '09 11:03

tfl


People also ask

What does sender() function do?

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.

What is sender object in c#?

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

What is object sender and EventArgs E in C# with example?

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


2 Answers

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 } 
like image 92
leppie Avatar answered Sep 23 '22 16:09

leppie


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

like image 20
Mark Kram Avatar answered Sep 24 '22 16:09

Mark Kram