“What is delegate?” we all have faced this question in one or more interview. 🙂 and the most common answer is “Function pointer”. Here I am showing a simple example of delegate. I have one user control and one aspx page. The user control contains one button. When user click on this button I will call a method on main page using delegate. Here is my user control,
<%@ Control Language=”C#” AutoEventWireup=”true” CodeFile=”WebUserControl.ascx.cs” Inherits=”Dalegate_WebUserControl” %>
<asp:Button ID=”btnTest” runat=”server” Text=”I am Inside User Control” OnClick=”btnTest_Click” />
Fig – (1) WebUserControl.ascx
On WebUserControl.ascx.cs I have written simple delegate and event handler as shown below,
public partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{
// Delegate declaration
public delegate void OnButtonClick(string strValue);
// Event declaration
public event OnButtonClick btnHandler;
// Page load
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
// Check if event is null
if (btnHandler != null)
btnHandler(string.Empty);
// Write some text to output
Response.Write(“User Control’s Button Click <BR/>”);
}
}
Fig – (2) WebUserControl.ascx.cs
Above code first check whether btnHandler is not null and than raise the event by passing argument. You can pass any number of argument in event. You need to change public delegate void OnButtonClick(string strValue) and btnHandler(string.Empty) lines for changing number of arguments. Now take a look at aspx page,
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”Dalegate_Default” %>
<%@ Register Src=”WebUserControl.ascx” TagName=”WebUserControl” TagPrefix=”uc1″ %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Label ID=”lblText” Text=”I am On Main Page : “
runat=”server”></asp:Label>
<asp:DropDownList ID=”ddlTemp” runat=”server”>
<asp:ListItem>Chirag</asp:ListItem>
<asp:ListItem>Dipak</asp:ListItem>
<asp:ListItem>Shailesh</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<uc1:WebUserControl ID=”WebUserControl1″ runat=”server” />
</div>
</form>
</body>
</html>
Fig – (3) Default.aspx
Default.aspx has one drop down list and a user control as shown in above code. Lets look at cs file,
public partial class Dalegate_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Declare and Define Event of User Control. When User Clicks on button
(which is inside UserControl)
// below event is raised as I have called raised that event on Button Click
WebUserControl1.btnHandler += new
Dalegate_WebUserControl.OnButtonClick(WebUserControl1_btnHandler);
}
void WebUserControl1_btnHandler(string strValue)
{
Response.Write(“Main Page Event<BR/>Selected Value: “ +
ddlTemp.SelectedItem.Text + “<BR/>”);
}
}
Fig – (4) Default.aspx.cs
Now when you run the application and clicks on button you can see that when user click on button the user control raise the click event and calls the WebUserControl1_btnHandler(string strValue) method on main page.
Happy Programming !!!
Why does everyone in hte picture at the top have their fingers taped up?
Oh, and thanks for the guideance on events.
Wilk,
Nice to see your comment. I am an Indian, we have kite flying festival on 14th January. All family members and friends gather at terrace and fly the kite for whole day. The string (cord) which is used to fly the kite is bit sharp so that we can cut other kites. Sometime this string may cut the fingers. So for protection of fingers we taped the fingers.
Hi ,
artical is good
thanks
i move one step through this artical
but my prob is
i have a user control
usercontrol is in master page
i have a contant page
contant page is in master page
when i clicked on usercontrol’s button
i want to capture that event in my contant page.
could u pls help me!!
thanks
hi guies,
its a really preety good article. i have also faced one problem like that. now i got the solution .thanks buddy…..
but i think u live in Ahemadabad. what u say ?
The following code is not working. giving me an error’ASP.webusercontrol_ascx.FrameworkInitialize()’: no suitable method found to override
The following code is not working. giving me an error’ASP.webusercontrol_ascx.FrameworkInitialize()’: no suitable method found to override
I want to call page_load event of one user control in another user control’s button click event .
How to call that?
I have tried in below way
user control1
Page_load(….)
{
if (!Ispostback)
{
if (session[“ddd”]!=nulll)
{
some code
……………
}
}
}
user control 2:
button click event
UserControl1 uc=new UserControl();
uc.page_load(this,e);
getting error ‘object reference not set to an instance of an object’ at lines Ispostback and Session[“ddd”]
and
I have tried by putting all the code of user control1’s page load event in one public method and tried to call that method in button click on user control 2
But no use…
Really good article.It helped me to handle event of user control from the parent page.
Thanks a lot….
Regards,
Hari Mohan
Nice article.. Thx
Ganesh
I have WebUserControl UCLogin, UCSell.
UCLogin i write:
void Page_Load(……)
{
Session[“UserName”] = UserName;
}
And UCSell i code:
void Page_Load(…..)
{
string User = (string)Session[“UserName”];
}
i replay User = “”
Who are khow about this problem ?
Thanks for help. I have been searching it since morining
Hi guys,
this is good.i hav one problem.
Button click event of asp.net page , Can i call usercontrol code using by delegate?or by another method?
Thanks
kathir
Thanks guys….
i had same problem with usercontrols.
its working fine
great work…
niranjana
hi,
i am getting error while accessing user control textBox,dropdown , in .aspx page
please help me to find solution
Hi
I am opening a page in which I have a command button(crysBtn) and would like to be clicked (automatically) when I pass the variables. How can I initiate the clicked event on the button?
Much appreciate your help.
REgards,
Ram!
Ram,
Do you want to initiate click event using javascript or from code behind? If you want to initiate from code behind you can write below code on page load,
crysBtn_Click(null,null);
Where crysBtn_Click is a name of event that fires when user clicks on the button.
Hi,
thanks for your mail. I can rather use the crys_btn(null, null). Hope that would resolve. Besides, I am curious to know how I can initiate a click event using JavaScript?
Is it something like, I should use a tag in the beginning of the page to enable to trigger the javascript?
<% @RegisterScript…….
Please correct me if I am wrong!
Tx,
Ram
Chirag!
One question. I tried your example that u posted. But, I am unable to display the value that I selected from the dropdown. Instead, I am getting the message from the User Control. Can you please guide me?
Tx and Regards,
Ram!
Soo Nice Guys …..thanks for the guideance on events.
Chirag Darji ,
I bought 1300 paged manual for C#.NET 2.0, they tried to explain that topic. I have read/tried their solutions many times. Unsuccesfully. But when I red your POST here, I finally understood. Thank you very much. Wish you all the best from Czech Republic.
I want to know how i can add a few delegate declerations for a few buttons on the UC page.
please reply with an answer.Thanx.
Hi ,
This code is not working in VB.Net.
It is showing the following error.
“reference to a non-shared member requires an object reference”
Can any one give the reply for this.
Thanks in advance
thank you for this helpful article it works great..
Hi !
Great Article !
But, I’m having an issue with dynamic user control…..
I mean, when I load my user control like this and adding it to a panel on main page , the event is not fired in main page :
MyUserControl uc = (MyUserControl)LoadControl(“MyUserControl.ascx”);
uc.OnClickProperty += new MyUserControl.OnClickDelegateEvent(MainPageMethod);
MyPanel.Add(us)
Any ideas or clues ?
This code works like a charm for me. You all saved me a ton of unnecessary web search time. This article was a easy read and easy to implement. Thanks.
Thanks, it is really nice.
I used this way to do:
I have two user controls (one parent, one child), I can use the delegate from child control in inform my parent control.
Well done and thanks.
good example for starter..Great example..Keep it up…
Article is really good. helped me a lot!!
USER CONTROL PAGE
public partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{
public delegate void OnButtonClick(string strValue);
public event OnButtonClick btnHandler;
protected void btnTest_Click(object sender, EventArgs e)
{
if (btnHandler != null)
btnHandler(string.Empty);
}
}
==============
ASPX PAGE:
PAGE_LOAD()
WebUserControl1.btnHandler += new Dalegate_WebUserControl.OnButtonClick(WebUserControl1_btnHandler);
}
void WebUserControl1_btnHandler(string strValue)
{
Response.Write(“Main Page EventSelected Value: “ +
ddlTemp.SelectedItem.Text + “”);
}
RAJNEESH HAJELA
MCTS
USER CONTROL PAGE
public partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{
public delegate void OnButtonClick(string strValue);
public event OnButtonClick btnHandler;
protected void btnTest_Click(object sender, EventArgs e)
{
if (btnHandler != null)
btnHandler(string.Empty);
}
}
==============
ASPX PAGE:
PAGE_LOAD()
WebUserControl1.btnHandler += new Dalegate_WebUserControl.OnButtonClick(WebUserControl1_btnHandler);
}
void WebUserControl1_btnHandler(string strValue)
{
}
RAJNEESH HAJELA
GWALIOR,M.P.
MCTS
another way:
Fantastic:
i want to use user control value on page.
i have two way :
i can go by property
or
we can do by delegate event
exp:
ascx:
public class Myeventargs:EventArgs
{
private string text;
public string Text
{
get{return text;}
set{text = value;}
}
}
——————–
public delegate void mYEventHandler(object sender,Myeventargs e);
public event mYEventHandler Eventtest;
protected virtual void OnEventtest(Myeventargs e)
{
if (Eventtest != null)
{
Eventtest(this, e);
}
}
—————————–
private void Button1_Click(object sender, System.EventArgs e)
{
Myeventargs objMyeventargs=new Myeventargs();
objMyeventargs.Text=TextBox1.Text;
OnEventtest(objMyeventargs);
}
———————————-
aspx page:
Eventhand.Eventtest+=new mYEventHandler(Eventhand_Eventtest);
private void Eventhand_Eventtest (object sender, Myeventargs e)
{
TextBox1.Text=e.Text.ToString();
}
try this:
u understand logic of delgate and event also.
u will do enjoy.
Rajneesh Hajela
Gwalior (M.P.)
MCTS
Very simple explanation and example. Worked for me. Thank You
Great tutorial. I was using Response.Redirect previously. But this is very clean solution.
hi,
u r best,
so
Wish you all the best .
I found another way to manage this, refer to this page
http://www.aspsnippets.com/Articles/Calling-Parent-Page-method-from-Child-Usercontrol-using-Reflection-in-ASP.Net.aspx
Hi All
I face a problem Like the Problem that Posted By Ankur in 2008
i have a user control Inside a master page
i have a contant page contant page is in master page
when i clicked on usercontrol’s button
i want to capture that event in my contant page
need a Help :”(
This is cool stuff , helps lot of people understand the basics.
I have been hunting the web for this. Your solution worked like a charm. thanks for sharing.
Great article. It help me much. Thank you.
Realy good example
Thank You guys,
I am so happy……….with ur code……….
Hi chiragrdarji,
I want to add this WebUserControl.ascx dynamically in the webpage.
And dynamically add the event raising code
WebUserControl1.btnHandler += new
Dalegate_WebUserControl.OnButtonClick(WebUserControl1_btnHandler);
How it is possible…
Please Help me..
Any way Thanks in advance for this post..
Regards,
Jiji Mathew.
They code to much… that’s why they all have their fingers all taped up 🙂 either that or they play a lot of cricket 🙂
Nice article 🙂
How to handle event When We HAve more than one User Controls on same PAge..?
Thanks , I got little understanding of events adn delagtes due to this article
Thanks! i found this article a lot better than others. thank u again.
what if the buttons is in the aspx and the dropdownlist is in ascx?
Hi,
Using Delegates only we need to call the Events in UserControl?Is there any other way like this finding the Control in the WebForm and calling the event?Can we do like this ?
Thanks & Regards,
Hemant V
Thank you so much, your code saved my precious time
Thank you for this example. How can a delegate be used in a senario where the main page contains the button? I have a gridview in the main page where each row contains a button. When clicking one of the buttons, I want to call a ModalPopupExtender in a user control to show a modal window. I’m having a hard time identifying the button in the main page. Thank you for your help.
Terry
Excellent article… and helped me a lot
Thanks for sharing
Very Good Articles related to delegates
Where did you use delegates in your project
C# Interview Questions on Delegates
First article I found that I can replicate successfully! This article works, make sure you watch when he says “WebUserControl1.btnHandler += new
Dalegate_WebUserControl.OnButtonClick(WebUserControl1_btnHandler);” That WebUserControl1 is the ID of the User Control in your ASPX!
Hey, thanks a lot, it was awesome.
I’m trying to do the same but assigning the WebUserControl1.btnHandler dinamically to one or another function, this works but the values of the controls changed inside those functions are reverted back upon exiting them…how would you do it correctly?
Good example
really super nice and so simple thank u sooooooooooooooo much dear frnd…….
Good Article But does not solve my problem.
1. We have one main page default.aspx
2. Update panel there
3. table inside the update panel
3. Left side of table has buttons to call the control in the placeholder kept in right of the table.
we are able to call the controls properly(dynamically loading user controls using loadcontrol and viewstate). Problem starts now since the controls are not statically added to default.aspx we are not able to call for usercontrols from the button inside the usercontrol. Say for example i clicked on button on on the lfethand of the table which loads usercontrol1.ascx in the placeholder1 now i have a button in usercontrol1 which is suppose to replace the usercontrol1 in the placeholder with usercontrol2 in the same placeholder.
Help is urgent.. my work is at standstill..
regards
bhargav
Why have this Q&A when no one replies to the posts
[…] essse link usando delegate, muito pratico..o melhor é a cara dos indianos kkkk Clique aqui pra ver o tutorial Compartilhe isso:CompartilharFacebookLinkedInTwitterGostar disso:GosteiSeja o primeiro a gostar […]
plz somebody help me. i am using usercontrol for gridview and want to get value of checked rows on my page.