Im my example iam trying to demonstrate how to send a TextBox content
in usercontrol(.ASCX Page) to a TextBox in Container page(ASPX Page) when user clicks
the Button in usercontrol(ASCX Page)
Screenshot of ASCX Page

ScreenShot of Container page (ASPX)

This sample lets the user control raise an event, which the parent page catches.
If u want to send data along with the event to the parent
page, in order this to happen, you can setup your own EventArgs class.
Just create a new class which inherits from System.EventArgs
class and then create properties like an ordinary class.
Creating a custom EventArgs Class
//Custom EventArgs Class
public class Myeventargs:EventArgs
{
private string text;
public string Text
{
get{return text;}
set{text = value;}
}
}
Declaring a delegate to handle your custom event
Now in the delegate declaration use Myeventargs as the parameter
in general we will be using the default parameter System.EventArgs for the Delegate
public delegate void mYEventHandler(object sender,Myeventargs e);
public class MyControl : System.Web.UI.UserControl
{
// ....
}
This creates a special event handler so now we can raise events elsewhere in our
application and state that the event is a mYEventHandler
Declaring and raising a public event for consumption
Now we have EventArgs Class as well as delegate it is time to create
and raise an event for user. Before raising an event first we need to declare the
event, this event declaration must be with in the class and should be like this.
public event mYEventHandler Eventtest;
protected virtual void OnEventtest(Myeventargs e)
{
if (Eventtest != null)
{
Eventtest(this, e);
}
}
Now you are ready to call this OnEventtest from some where
in the MyControl class. How you do this depends on what should cause the event to
occur. Before raising this custom event you have to create an object for Myeventargs
class and pass this object to the OnEventtest method.
private void Button1_Click(object sender, System.EventArgs e)
{
Myeventargs objMyeventargs=new Myeventargs();
objMyeventargs.Text=TextBox1.Text;
OnEventtest(objMyeventargs);
}
Consuming Events in ASPX Page
In order to consume the event from the user control u have to first
register that user control in the. aspx page .
<%@ Register TagPrefix="Events" TagName="BtnTxt" Src=" MyControl.ascx" %>
<Events:BTNTXT id="Eventhand" runat="server"></Events:BTNTXT>
In. aspx page declare this custom control at the class level
protected CSharpThreads.Usercontrol Eventhand;
In order to capture the event from the custom control , you have to do the event
initialization.
private void InitializeComponent ()
{
Eventhand.Eventtest+=new mYEventHandler(Eventhand_Eventtest);
}
This is the event, which is captured from the custom control.
private void Eventhand_Eventtest (object sender, Myeventargs e)
{
TextBox1.Text=e.Text.ToString();
}
|