Monday, June 19, 2006

.NET FAQ: Can A Button-Click Event on One Window Be Handled by Another?

Well, while this is entirely possible, you should avoid doing so. There are good reasons for this recommendation. Tow important ones are:
1) The button-click events are handled through .NET event model, in which when an event occurs, the associated delegate will be called. The delegate is a private member function of the form class. Letting another form to handle this event will break the protection of the delegate function.
2) When the delegate is called, the sender object is passed as an input parameter. In this case, it is the button that has been clicked. Again, the button object usually is a private data member of the form class. Letting another form to handle this event will inevitably expose the button object to tat foreign form.

Are there other ways that the button click on one window (Form A) can be handled by another (Form B)? Yes. Within the event handler, Form A can call into Form B in any proper way you want. For example, in the event handler, you may define a button-type (or click-type) parameter and pass it to the callback function of Form B. Then, Form B can take different actions based on the button parameter from Form A.

0 Comments:

Post a Comment

<< Home