Powered by Blogger.

Tuesday, July 20, 2010

Simple custom Event & Delegates demonstration.


Hi,
The article will help you to fire your events (custom events) from the control's events of a Web User Control from the Web Page.

Not going into Much of the theories,I am mentioning the code below to be used for User Control and Web Page.

In my case here i want to fire a Button's Click event from my web page.
You can in mean way can achieve any event like Drop down's SelectedIndexChanged, Data Grid's Paging , Sorting, Command event or any one of any control by just changing the parameter types of the arguments in the Delegate that you are creating the object of.


Here the Code goes of User Control:

public partial class WebUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public delegate void MyDel(object sender, EventArgs e);
    //The argument's types above will be as of the event you want to call your manual event in.

    public event MyDel evn; // Event of the above delegate
    protected void Button1_Click(object sender, EventArgs e)
    {
        evn(sender, e);
        //Call this manual event inside the event you want to handle from the Web Page.
    }
}

Here the Code goes of Web Page:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebUserControl1.evn += new WebUserControl.MyDel(WebUserControl1_evn);
        // Define the function pointer in which you will create the custom rules or business rule as per requirement
        //So when ever the event of the button in the user control will fire, this event handler will be called
    }

    void WebUserControl1_evn(object sender, EventArgs e)
    {
        if(Request["a"] == null) //Condition 1
        {
            Response.Write("asdfasdf");
        }
        else
        {
            Response.Write("asdfasdfadfasdfasdf");
        }
    }
}

I wish this will give you a good idea and will solve the problems of many people of controling the events of Web User Control's Controls from the page.

Also please try for other events of other controls and let me know your feedback.

by Puneet20884

No comments:

Post a Comment

  ©Template by Dicas Blogger.

TOPO