How To Access One UserControl from Another Using ASP.NET

Posted by: Suprotim Agarwal , on 5/16/2008, in Category ASP.NET
Views: 112626
Abstract: In this article, we will explore how to access the properties and control of one usercontrol from another using ASP.NET.
How To Access One UserControl from Another Using ASP.NET
 
Recently, I came across a post in the asp.net forums, where a user was trying to access the value of a dropdownlist kept in one UserControl, from another UserControl. There were quiet a number of suggestions given, however either they were too complex or not explained well. In this article, we will see how easy it is to achieve this requirement.
Step 1: Create a new ASP.NET website. Right click the project > Add New Item > Web User Control. Give it the name ‘ControlA’. Similarly create another user control and give it the name ‘ControlB’.
Step 2: We will now create a dropdownlist(ddlItems) in ‘ControlB’ and access the selected value of the dropdownlist in 'ControlA’.
To do so, drag and drop a dropdownlist in the usercontrol ‘ControlB’ and add some items to it. The source will look similar to the following:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ControlB.ascx.cs" Inherits="ControlB" %>
<asp:DropDownList ID="ddlItems" runat="server">
    <asp:ListItem>Item A</asp:ListItem>
    <asp:ListItem>Item B</asp:ListItem>
    <asp:ListItem>Item C</asp:ListItem>
</asp:DropDownList>
 
Also expose the dropdownlist as a property as shown below:
C#
public partial class ControlB : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    public DropDownList ControlB_DDL
      {
            get
            {
                return this.ddlItems;
            }
     }
}
VB.NET
Public Partial Class ControlB
      Inherits System.Web.UI.UserControl
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
 
      End Sub
 
      Public ReadOnly Property ControlB_DDL() As DropDownList
                  Get
                        Return Me.ddlItems
                  End Get
      End Property
End Class
Step 3: Now drag and drop a TextBox(txtDDLValue) and a Button(btnDDLValue) on to the usercontrol ‘ControlA’.
Another crucial part is to add a Reference directive of ‘ControlB’ in ‘ControlA’. Since the user controls are compiled into assemblies, adding a reference enables ‘ControlA’ to access the methods and properties of ‘ControlB’. The source will look similar to the following:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ControlA.ascx.cs" Inherits="ControlA" %>
<%@ Reference VirtualPath="~/ControlB.ascx" %>
 
 
<asp:TextBox ID="txtDDLValue" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnDDLValue" runat="server" OnClick="btnDDLValue_Click" Text="Get DropDown Value" />
 
Add the following code to the codebehind of ‘ControlA’
C#
public partial class ControlA : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    protected void btnDDLValue_Click(object sender, EventArgs e)
    {
        ControlB ctrlB = (ControlB)Page.FindControl("cB");
        DropDownList ddl = ctrlB.ControlB_DDL;
        txtDDLValue.Text = ddl.SelectedValue;
    }
}
VB.NET
Public Partial Class ControlA
      Inherits System.Web.UI.UserControl
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
 
      End Sub
 
      Protected Sub btnDDLValue_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim ctrlB As ControlB = CType(Page.FindControl("cB"), ControlB)
            Dim ddl As DropDownList = ctrlB.ControlB_DDL
            txtDDLValue.Text = ddl.SelectedValue
      End Sub
End Class
Since we have referenced ‘ControlB’ in ‘ControlA’, we can find the control and access the dropdownlist, that was exposed as a property in Step 2.
Step 4: All you have to do now is to add the user controls on to the page(default.aspx). To do so, add the Register directive to register both the user controls and then use the usercontrols. The source will look similar to the following:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/ControlA.ascx" TagName="ControlA" TagPrefix="ctrlA" %>
<%@ Register Src="~/ControlB.ascx" TagName="ControlB" TagPrefix="ctrlB" %>
 
 
<!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>Pass Message From One UserControl To Another</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ctrlA:ControlA id="cA" runat="server" />
        <br />
        <br />
        <br />
        <ctrlB:ControlB ID="cB" runat="server" />
    </div>
    </form>
</body>
</html>
Run the application. Change the value of the dropdownlist in ‘ControlB’. Now click the button in ‘ControlA’ and the selected value of the dropdownlist will appear in the textbox.
That was quiet simple. Your requirement may not be as simple as the one demonstrated in this article, however the basics of accessing one user control from another usercontrol will remain the same. I hope this article was useful and I thank you for viewing it.
 
If you liked the article,  Subscribe to my RSS Feed.
  
  
 
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Johannes Hansen on Saturday, May 24, 2008 12:21 PM
While this is a simple and effective method of communication between your controls it does also create a rather brittle dependency from ControlA to ControlB. So ControlA can never exist on a page without ControlB although the opposite is not the case.

Now, your project might merit this simple/easy method of communication but I wouldn't recommend it on larger projects. Since these types of dependencies always give you a hard time down the road and are hard to manage.

In larger projects I would rather recommend that you use an event broker model. Such as the event broker sample in the new Unity IoC container from patterns and practices.
Comment posted by Suprotim Agarwal on Wednesday, May 28, 2008 8:47 AM
Hi,
Good suggestion Johannes. I had read about it while reading about CAB.

The article posted here was in response to a post asked in the asp.net forums. Can you share an article for the users
describing the concept in detail.
Comment posted by chow on Monday, June 2, 2008 1:22 PM
hi thx
Comment posted by chow on Monday, June 2, 2008 1:23 PM
bh
Comment posted by chow on Monday, June 2, 2008 1:24 PM
dfds
Comment posted by chow on Monday, June 2, 2008 1:24 PM
fcnbgfh
Comment posted by Dhanaraj on Thursday, June 19, 2008 8:31 AM
really nice article author. The article describes the communication between user controls.
thank u
Comment posted by Sheo Narayan on Friday, July 11, 2008 10:21 PM
If interested to pass value from User control to the page or vise versa, see this article http://dotnetfunda.com/articles/article97.aspx
Comment posted by Vijay on Tuesday, July 22, 2008 7:25 AM
If there are more number of user controls this will become confusing...
Comment posted by Rob on Thursday, August 14, 2008 12:29 PM
What is cB in this line: ControlB ctrlB = (ControlB)Page.FindControl("cB");
Comment posted by Rob on Thursday, August 14, 2008 12:33 PM
Nevermind. I figured it out :)
Comment posted by Danish on Tuesday, August 19, 2008 11:55 AM
nice one
Comment posted by Tony on Thursday, August 21, 2008 11:04 AM
I havn't figured out what cB is?

;)
Comment posted by Suprotim Agarwal on Thursday, August 21, 2008 9:15 PM
Tony: Check out the declaration of the two controls:

<ctrlB:ControlB ID="cB" runat="server" />
Comment posted by Ryan on Friday, September 5, 2008 10:27 AM
nice article, but my ControlB ctrlB = (ControlB)Page.FindControl("cB") always returns nothing??!
Comment posted by Kevin on Wednesday, September 10, 2008 9:06 AM
I have the same problem as Ryan (above).  My controlB always returns a null.  Any ideas on how to fix this or on what we're doing wrong?
Comment posted by Kevin on Wednesday, September 10, 2008 9:23 AM
Aha!  I found the reason why my controlB returned null.  

I am using controls that are located in an asp.net master page.  In order to access them, I needed to use Page.Master.FindControl.

Thanks for the walkthrough!
Comment posted by Suprotim Agarwal on Wednesday, September 10, 2008 1:00 PM
Ryan, Kevin: Great to know that you solved the issue!!
Comment posted by Jeremy L. on Friday, October 3, 2008 1:46 PM
Thank you tremendously for writing this. I read several examples already, and as you stated, none did a very good job of explaining it, or used overcomplicated code. This was easy to understand, and I appreciate that it was explained as a single tiny project so that I could build it on my own and see how the logic works together.
Comment posted by Jeremy L. on Friday, October 3, 2008 2:45 PM
Thank you tremendously for writing this. I read several examples already, and as you stated, none did a very good job of explaining it, or used overcomplicated code. This was easy to understand, and I appreciate that it was explained as a single tiny project so that I could build it on my own and see how the logic works together.
Comment posted by Suprotim Agarwal on Friday, October 3, 2008 11:15 PM
Jeremy: Glad to hear that the article was helpful :)
Comment posted by hemant gaur on Monday, January 12, 2009 8:44 PM
Hi,
I am getting a squigly line at "Dim ctrlB As ControlB" under ControlB.  Says Type not defined.  I even changed the class controlB from partial to partial public.  I am on ASP.NET 2.0
Comment posted by amit on Tuesday, August 11, 2009 2:31 AM
it's good but it doesn't work with master page.
Comment posted by Swaroop on Sunday, October 11, 2009 4:26 AM
Hi..the article is really nice..
i have one other requirement similar to this.
I want to write a javascript function in the codebehind of usercontrolA to be used(run) on the usercontrolB on the page load.
How to achieve this?  
Please reply I am in real hurry. Thanks.
Comment posted by Swaroop on Sunday, October 11, 2009 4:28 AM
I dont know why my comment is being posted so many times..i am sorry..please reply.
Thanks.
Comment posted by srinu on Thursday, December 17, 2009 1:44 AM
nice work..thanks a lot
Comment posted by sumit kuamr on Tuesday, March 9, 2010 5:01 AM
Help
Comment posted by niio on Tuesday, March 23, 2010 7:40 AM
much  thx for this post and discussion. I tried 8hours to acces one control from another. this really helps me, also the discussion when the findcontrol returns null: page.master.findcontrol :)
Comment posted by Gabriel Rosario on Tuesday, July 6, 2010 4:48 PM
i can set value or execute control method from one control to another., too.
Comment posted by smith on Tuesday, July 27, 2010 12:12 PM
I am getting user control not defined in the user control when i do the above way..wt i am missing?
Comment posted by Dienekes on Monday, August 2, 2010 12:33 AM
This code doesn't work. Reference of one UC in anothe isn't available..
Comment posted by DenoReno on Monday, September 27, 2010 3:51 PM
do I have to code this line somewhere:

<ctrlB:ControlB ID="cB" runat="server" />
Comment posted by Chanchal on Thursday, September 30, 2010 2:10 AM
Thanks
Comment posted by Chanchal on Thursday, September 30, 2010 2:51 AM
Thanks
Comment posted by siva on Tuesday, January 4, 2011 1:17 AM
Very simple and nice article,everybody can understand easily
Comment posted by Dawg on Thursday, February 24, 2011 3:26 PM
page.master.findcontrol was EXACTLY what I was looking for! Thanks.
Comment posted by Rohan Patil on Sunday, March 13, 2011 10:42 PM
If Control A contains more the 10 child control or 20 properties then ?
Is there any way to Inherit the Control_A and Control_B  with all the properties and functionality .
Comment posted by Adam on Tuesday, April 26, 2011 4:28 PM
At this line: ControlB ctrlB = (ControlB)Page.FindControl("cB")

I get the following error:

CS0246: The type or namespace name 'ControlB' could not be found (are you missing a using directive or an assembly reference?

Help, please?


Comment posted by Adam on Tuesday, April 26, 2011 4:44 PM
At this line: ControlB ctrlB = (ControlB)Page.FindControl("cB")

I get the following error:

CS0246: The type or namespace name 'ControlB' could not be found (are you missing a using directive or an assembly reference?

Help, please?


Comment posted by Brian Hudson on Sunday, June 19, 2011 10:35 AM
I think this is a very good article and shows it very clearly.  I would like to know how to do the same thing on a Windows Form (not on a webform).  It doesn't matter if you show it in C# or in VB.NET as long as it is on a winform.  Please can anybody help with this - i think the main differenc ewill be with this code: ControlB ctrlB = (ControlB)Page.FindControl("cB");
Comment posted by Ajay Kumar on Thursday, December 1, 2011 4:33 AM
I am facing one problem regarding DropDownList control in ASP.Net using C#.
When I select an item from DropDownList1 that item also show in another DropDownList2 without clicking any control.
Comment posted by Fabio D on Saturday, January 7, 2012 6:41 AM
Try change from ControlB ctrlB = (ControlB)Page.FindControl("cB")
to ControlB ctrlB = (ControlB)Parent.FindControl("cB")
Comment posted by somu on Friday, June 15, 2012 7:22 AM
kkkkkkkk.......
Comment posted by vyshak on Sunday, June 17, 2012 11:07 PM
thank you. it was realy nice
Comment posted by ManojKB on Monday, June 18, 2012 12:13 AM
when using master page this is not working. it fail to find control why?
Comment posted by vyshak on Monday, June 18, 2012 12:56 AM
if you are using master page, please try this
ControlB ctrlB = (ControlB)Page.Master.FindControl("ContentPlaceHolder1").FindControl("cB");
Comment posted by ycdeng on Tuesday, July 10, 2012 5:26 PM
how to get ctrlB when using nested master pages?
Comment posted by Steven Correia on Friday, July 27, 2012 9:32 AM
hi i have tried the same approch but it doesn't work for me... i have created a web application and not web site. Could this be problem. here is the code i have used in both the user controls.

User control 1
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text = "Lamborghini" Value ="1"> </asp:ListItem>
<asp:ListItem Text = "Ferrari" Value ="2"> </asp:ListItem>
<asp:ListItem Text = "Pagani Zonda" Value ="3"> </asp:ListItem>
<asp:ListItem Text = "Maserati" Value ="4"> </asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />

User control 2(which this is trying to access controls inside Usercontrol 1

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl2.ascx.cs" Inherits="WebApplication1.WebUserControl2" %>
<%@ Reference VirtualPath="~/WebUserControl1.ascx" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text = "Honda" Value ="1"> </asp:ListItem>
<asp:ListItem Text = "Toyota" Value ="2"> </asp:ListItem>
<asp:ListItem Text = "Nissan" Value ="3"> </asp:ListItem>
<asp:ListItem Text = "Sonata" Value ="4"> </asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

//CS file
    public partial class WebUserControl2 : Class1
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string txt = Text;
            WebUserControl1 ctrlB = (WebUserControl1)Page.FindControl("cA");

            DropDownList ddl = ctrlB.ControlB_DDL;

            TextBox1.Text = ddl.SelectedValue;
        }
Comment posted by Steven Correia on Friday, July 27, 2012 9:53 AM
hi i have tried the same approch but it doesn't work for me... i have created a web application and not web site. Could this be problem. here is the code i have used in both the user controls.

User control 1
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text = "Lamborghini" Value ="1"> </asp:ListItem>
<asp:ListItem Text = "Ferrari" Value ="2"> </asp:ListItem>
<asp:ListItem Text = "Pagani Zonda" Value ="3"> </asp:ListItem>
<asp:ListItem Text = "Maserati" Value ="4"> </asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />

User control 2(which this is trying to access controls inside Usercontrol 1

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl2.ascx.cs" Inherits="WebApplication1.WebUserControl2" %>
<%@ Reference VirtualPath="~/WebUserControl1.ascx" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text = "Honda" Value ="1"> </asp:ListItem>
<asp:ListItem Text = "Toyota" Value ="2"> </asp:ListItem>
<asp:ListItem Text = "Nissan" Value ="3"> </asp:ListItem>
<asp:ListItem Text = "Sonata" Value ="4"> </asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

//CS file
    public partial class WebUserControl2 : Class1
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string txt = Text;
            WebUserControl1 ctrlB = (WebUserControl1)Page.FindControl("cA");

            DropDownList ddl = ctrlB.ControlB_DDL;

            TextBox1.Text = ddl.SelectedValue;
        }
Comment posted by Steven Correia on Friday, July 27, 2012 10:04 AM
hi i have tried the same approch but it doesn't work for me... i have created a web application and not web site. Could this be problem. here is the code i have used in both the user controls.

User control 1
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text = "Lamborghini" Value ="1"> </asp:ListItem>
<asp:ListItem Text = "Ferrari" Value ="2"> </asp:ListItem>
<asp:ListItem Text = "Pagani Zonda" Value ="3"> </asp:ListItem>
<asp:ListItem Text = "Maserati" Value ="4"> </asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />

User control 2(which this is trying to access controls inside Usercontrol 1

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl2.ascx.cs" Inherits="WebApplication1.WebUserControl2" %>
<%@ Reference VirtualPath="~/WebUserControl1.ascx" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text = "Honda" Value ="1"> </asp:ListItem>
<asp:ListItem Text = "Toyota" Value ="2"> </asp:ListItem>
<asp:ListItem Text = "Nissan" Value ="3"> </asp:ListItem>
<asp:ListItem Text = "Sonata" Value ="4"> </asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

//CS file
    public partial class WebUserControl2 : Class1
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string txt = Text;
            WebUserControl1 ctrlB = (WebUserControl1)Page.FindControl("cA");

            DropDownList ddl = ctrlB.ControlB_DDL;

            TextBox1.Text = ddl.SelectedValue;
        }
Comment posted by samba on Friday, October 19, 2012 2:09 AM
Thank You. Helpful.
Comment posted by Isaac Samuel on Monday, May 13, 2013 2:46 AM
I have two user controls, I want when I select a value from the dropdownlist of controlA the SelectedIndexChanged event in the ControlA to populate the Dropdownlist of ControlB based on the selected value from ControlA. I have tried this several times and the issue I got is NullReferenceException was unhandled by user code(object reference not set to an instance of the object)

When I stepped through the codes at runtime, the controlB I try to find returns null.
Comment posted by Karin on Thursday, July 11, 2013 12:06 PM
This is a brute force method, but it works because it was buried so far down in the hierarchy of controls it was the only way I could find it:
        private Control GetTextEditor(ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl.ID != null && ctrl.ID == "teMessage")
                    return ctrl;
                if (ctrl.Controls.Count > 0)
                {
                    Control inner = GetTextEditor(ctrl.Controls);
                    if (inner != null)
                        return inner;
                }
            }
            return null;
        }
Comment posted by Vishal Gaikwad on Wednesday, July 24, 2013 8:33 AM
This is very good article given steps by steps.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel