Click here to Skip to main content
15,896,730 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Let's say I have custom Web User Control named usercontrol1, where an event Event1 can occure.

I'd like to run some function on page, that contains this usercontrol.

The obvious way is to asign a delegate:

C#
public partial class UserControl1 : System.Web.UI.UserControl
{
    public event EventHandler Event1;

    // ... code here ...
}


C#
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Init(object sender, EventArgs e)
    {
        usercontrol1.Event1+=this.some_function;
    }

    protected void some_function(object sender, EventArgs e)
    {
         // what should be done after event raised...
    }

    // other code
}

However I would like to assign an event on aspx file of base page, like this:

HTML
<UserControl1 name="usercontrol1" OnEvent1="some_function" />

How can this be done? I'd appreciate any help. :)
Posted
Comments
Sergey Alexandrovich Kryukov 6-Oct-14 10:38am    
There is not such thing as "assign an event". The operator += adds an event handler to the invocation list of an event instance. Also, event instances are immutable. A brand new instance is created under the hood.
—SA

1 solution

The OnEvent1 part should be there automatically if you declared the event right...
See this sample...

Control code:
C#
public partial class WebUserControl1 : System.Web.UI.UserControl
{
    public event EventHandler TextUpdated;

    public string Text
    {
        get
        {
            return ( TextBox1.Text );
        }
    }

    protected void TextBox1_TextChanged ( object sender, EventArgs e )
    {
        if ( TextUpdated != null )
        {
            TextUpdated( this, EventArgs.Empty );
        }
    }
}


Page markup:
ASP.NET
<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="Control" TagName="WebUserControl1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <Control:WebUserControl1 runat="server" OnTextUpdated="Unnamed_TextUpdated" />
        </div>
    </form>
</body>
</html>


The important parts are in bold!
 
Share this answer
 
Comments
Camasutrinho 6-Oct-14 6:14am    
Didn't know that. Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900