Search code examples
c#asp.netasp.net-customcontrol

access property of asp.net custom control from code behinde


I create a asp.net custom control

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="control.ascx.cs" Inherits="test.control.control" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

I have drop it in an aspx page and I want to use Text property of the custom control but the custom control does not have Text property.

<uc1:control runat="server" id="control" />

Solution

  • You need to add a property to your code behind that represents the text property of the textbox.

    So within control.ascx.cs

    public string Text
    {
        get { return TextBox1.Text; }
        set { TextBox1.Text = value; }
    }
    

    Then this will work

    <uc1:control runat="server" id="control" Text="My Control" />
    

    Just to clarify - custom controls don't naturally inherit the properties of the child controls, for example, what would you expect to happen if the control had 2 textbox controls? So for each property that you want your custom control to expose you need to add a property to the code behind. You can even add properties that don't relate to the properties of the child controls and keep the value in a hidden field or control state or even viewstate.