Search All Articles Submit your Website or Blog to A New Internet Library
Thursday, October 23, 2008
How to pass values from User Control to Page or calling Page methods from User Control.
Explanation:
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;
}
}
Also Read other Top Articles
- JSON Serialization in VS 2008
- Implementing Forms Authentication in Silverlight Application.
- Making GridView Rows or Individual Cells Clickable and Selectable.
- Enabling browser back button for GridView Paging and Sorting in Ajax 1.1 and 3.5 (using Visual Studio 2005/ Visual studio 2008)
- How to pass values from User Control to Page or calling Page methods from User Control.
- What is WCF?
- New features in C# 4.0
- C# to VB.NET and VB.NET to C# online free converter tools.


4 comments:
Nice one
How to implement same thing using AJAX
awesome!!!
Thanks so much! Your article has been a tremendous help and was easy for me to understand.
Post a Comment
Post your comments/questions/feedback for this Article.