Say we have a TextBox and Button control in one user control and we have another TextBox in .aspx Page in wich we have placed that User Control. And now If the user enters any text in User Control TextBox and clicks on Button in User Control, that text should be displayed in .aspx page TextBox by calling a method in page on User Control button click.
Solution:
This can achived by using Events and Delegates.
Lets treat User Control as publisher class and .aspx Page as Subscriber class.
Now declare Delegate type in User Control and also declare public Event with that delegate type in user control class.
In the User Control Click event raise that event by passing User Control textBox text as input, then all the Event Handlers subscribed to that event will be fired.
User Control Code:
using System;
using System.Data;
…..
//Declare Delegate Type
public delegate void Mydelegate(string text);
public partial class WebUserControl : System.Web.UI.UserControl
{
//Declare event with MyDelegate delegate type.
public event Mydelegate MyEvent;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UCButton_Click(object sender, EventArgs e)
{
// Check if MyEvent is not null i.e atleast one Event Handler is subscribed to event.
if(MyEvent != null)
{
MyEvent(UCTextBox.Text);
}
}
}
Then in .aspx Page create a method say SetTextBoxText in which input text is set to Page
TextBox. Then in Page_Load of Page subscribe SetTextBoxText method to event declared in User Control.
ASPX Page Code:
using System;
using System.Data;
………
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Subscribe SetTextBoxText Event Handler to MyEvent.
WebUserControl1.MyEvent += SetTextBoxText;
}
protected void SetTextBoxText(string text)
{
//Set Page Text Box with Input value.
PageTextBox.Text = text;
}
}
ref: http://interviews.dotnetthread.com/2008/10/how-to-pass-values-from-user-control-to.html