Article shows how to call a control click event of another web form programmatically.
Consider an example with MasterPage.master having a button click event and we want to call this event from a Content Page on Page_Load. How to do?
We can achieve this by using IPostBackEventHandler (Defines the method ASP.NET server controls must implement to handle postback events) raising/calling RaisePostBackEvent (When implemented by a class, enables a server control to process an event raised when a form is posted to the server).
Step1: Using FindControl method to get the button of MasterPage.master.
Button btn1 = new Button();
btn1 = (Button)Master.FindControl("Button1");
Step 2: Calling the button postback event using IPostBackEventHandler method.
((IPostBackEventHandler)btn1).RaisePostBackEvent(null);
Here RaisePostBackEvent method passing a null value as EventArgs for the event.
The registered methods must not attempt to do anything with it. We can define an EventArgs also.
((IPostBackEventHandler)btn1).RaisePostBackEvent(new System.EventArgs().ToString());
Now run the project, we will get an Invalid postback or callback argument.
This error can be overcome by adding EnableEventValidation="false" ValidateRequest="false" on <%@ Page directory of Form1.
Caution: When request validation is disabled, it is the responsibility of the developer to ensure that content is properly encoded or processed before submission.
In this way we can handle DropDownList and ListBox.
This time we are working with postback data, so the method used is IPostBackDataHandler (Defines methods that ASP.NET server controls must implement to automatically load postback data) raising/calling RaisePostDataChangedEvent (When implemented by a class, signals the server control to notify the ASP.NET application that the state of the control has changed).
RaisePostDataChangedEvent (also works with TextBox control) methods invokes the OnTextChanged method.
DropDownList ddl1 = new DropDownList();
ddl1 = (DropDownList)Master.FindControl("DropDownList1");
((IPostBackDataHandler)ddl1).RaisePostDataChangedEvent();
Sample code attached.
About Event-Based Programming
Already we have a good chapter By Apress regarding above topics, refer link.
(http://www.c-sharpcorner.com/uploadfile/freebookarticles/apress/2009jan02050545am/EventBasedProgramm/1.aspx)
Hope this article helps you. Post your comments.