C# – How to disable user control from code-behind

asp.netcnetuser-controlswpf

I have 2 user controls in an ASPX page. By default the second user control should be disabled. In that user control i am having only one text box. So i find the control in the page load event like this:

TextBox txtLocation = (TextBox)PI_CompLocationTree.FindControl("txtLocation");
txtLocation.Enabled = false;

But i am getting txtLocation as null. How do I get the control in the ASPX page from the ASCX control?

My Updated Code..In Aspx page..

<%@ Register Src="~/UserControl/PI_CompLocationTree.ascx" TagName="PI_CompLocationTree"
TagPrefix="uc1" %>

 <div id="Div2">
   <div class="location">
      <div class="usLocation">
           <uc1:PI_CompLocationTree ID="PI_CompLocationTree1" runat="server"/>
       </div>
   </div>
 </div>

In Page Load…

 PI_CompLocationTree PI_CompLocationTree = new PI_CompLocationTree();

 protected void Page_Init(object sender, EventArgs e)
 {
    var userControl = (PI_CompLocationTree)this.FindControl("PI_CompLocationTree1");
    userControl.EnabledTextBox = false;
 }

In ASCX Page…

<asp:TextBox ID="txtLocation" CssClass="fadded_text fadded_text_ctrl" Style="width: 260px;
float: left;" runat="server" Text=""></asp:TextBox>

In ASCX Code Behind…

public partial class PI_CompLocationTree : System.Web.UI.UserControl
{
    public bool EnabledTextBox
    {
        get { return txtLoc.Enabled; }
        set { txtLoc.Enabled = value; }
    } 
}

Best Answer

Use FindControl Methods as Follow..

1.  UserControlClass objOfUserControl = (UserControlClass)Page.FindControl("UserControlID");
    TextBox txtLocation= objOfUserControl.FindControl("txtLocation");
    txtLocation.Enabled = false; 

2.You Can Also use Public Property as Follow

In User Control Codebehind

public bool TextBoxUSC
{
  set{txtLocation.Enabled = value;}
}

In Aspx Code Behind

UserControlClass.TextBoxUSC=false;

If You are using Master Page

    ContentPlaceHolder cph = (ContentPlaceHolder)this.Page.Master.FindControl("MainContent");//"MainContent" is ContentPlaceHolder's ID

    UserControlClass userCntrl = (UserControlClass)cph.FindControl("UserControlID");
    userCntrl.TextBoxUSC = false;
Related Topic