How to access a control in a web user control from its parent page

By Mohammad Mahdi Ramezanpour at October 17, 2008 21:45
Filed Under: ASP.NET, .NET General

Yesterday I was answering some questions in ASP.NET forums. One of the questions I answered was “How can I access a TextBox control in a web user control from an .aspx page”.

Today I decided to post this blog to explain how you can do it.

It’s like a piece of cake. I create a web user control named “WebUserControl.ascx” and add a TextBox to it like following:

<%@ Control Language="C#" AutoEventWireup="true" 
CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:TextBox runat="server" ID="TB_Test"></asp:TextBox>


Then, I create a web form named “Default.aspx” and add my user control to it:

<%@ Page Language="C#" AutoEventWireup="true"  
CodeFile="Default.aspx.cs" Inherits="_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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
        <asp:Button ID="Button1" runat="server" 
        onclick="Button1_Click" Text="Button" />
    
    </div>
    </form>
</body>
</html>

As you can see, I also added a button control that reads value of our TextBox in web user control and then write it to the page. Let’s see the event handler of Button1.Click:

    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox t = (TextBox)WebUserControl1.FindControl("TB_Test");
        Response.Write(t.Text);
    }

The nice part is the use of FindControl method that gives a control that I’m looking for.

Finally, I just used a simple cast in order to convert the returned control from FindControl method. Because my control was a TextBox, I created a variable as a TextBox and then fill it with my casted control. When I cast it, I can access all properties and methods related to this control.

Comments are closed

Currently Reading

Quote of the day

Send Persian SMS