Alex Rivera | Logout

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

Asked 2009-03-11T11:18:03.933
33

I have an event handler for a Textbox and 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. 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 :-)

Edit
Report

1 Answer

0

If the code is identical, do you need to care? I wonder if casting to Control wouldn't give you everything you need...

One complex handler is not necessarily better than several simple handlers. Either way, if you have to go this route, "as"/"is" is preferable (it isn't dependent on strings etc):

TextBox tb = sender as TextBox;
if(tb!=null) {/* TextBox specific code */}
...
answered 2009-03-11T11:22:57.760

Your Answer