HOw to Raise Events in an ASCX User Control (Is it better in ASPNET 2.0 ?)

A

Anonieko

This is what you have to hand-write



Raise Events From ASP.NET ASCX User Controls

Drop a UserControl called MyControl.ascx into a page.

To add a member variable to the container class, you can simply add the
line (C#):

protected MyControl MyControl1;



STEPS IN RAISING EVENTS FROM ASP.NET ASCX USER CONTROLS.
========================================================

USERCONTROL.ASCX.CS
-------------------

1. Define a public member

public event System.EventHandler TabClicked;



2. Raise it whenever you want like this:

if(this.TabClicked != null)
this.TabClicked(this, new EventArgs());




PARENTPAGE.ASPX.CS
------------------

1. Drag and Drop the control.

2. Add in the Page_Load or Init the wire code


this.MyControl.TabClicked +=new
EventHandler(MyControl_TabClicked);

3. Write the Handler

private void MyControl_TabClicked(object sender, EventArgs e){ /*
etc... */ }



If you type "this.MyControl.TabClicked +=" in the IDE, an press TAB
twice



PASSING DATA
============


Now, say you wanted to pass some specific data to the container
control.

One way is to use a delegate. This comes in really handy, and is in
fact quite easy too.
For example, what if you wanted to pass some private value from the
encapsulated child class?

1. First create a custom class deriving from System.EventArgs with a
member variable
that contains your interesting private value:

public class TabClickEventArgs : EventArgs
{
private String myString;
public String MyString
{
get { return myString; }
set { myString = value; }
}
}

2. Then create a delegate for your event like so:

public delegate void TabClickEventHandler(object sender,
TabClickEventArgs e);


The rest is just like before, except that you define your custom event
hander,
instead of the basic System.EventHandler.

public event TabClickEventHandler TabClicked;

And raise it like so.

// Raise the tabclicked event.
if(this.TabClicked != null)
{
TabClickEventArgs e = new TabClickEventArgs();
e.SomeString = "test";
this.TabClicked(this, e);
}

Finally, when you wire the event up, your method signature for the
handler,
just needs to match the signature of your delegate:

private void MyControl_TabClicked(object sender, TabClickEventArgs
e) {}

-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top