Search code examples
c#htmlasp.netwebformsmarkup

How to disable a control inside a User Control


I thought this would be a simple thing to accomplish but am having some issue. My initial asp.net markup for the server control looks like this:

<ucTextArea:UserControlTextArea ID="taRemarks" runat="server" />

However, in the code behind, I have a conditional statement that checks for user rights in order to enable this text field or not, something like this:

if (CurrentUser.AccountTypeID == 4 || CurrentUser.AccountTypeID == 6)
    taRemarks.Attributes.Add("enabled", "");
else
    taRemarks.Attributes["disabled"] = "true";

Above are two ways I have tried to accomplish this, but haven't worked when rendered in the browser. How can I disable this server control?

Edit: The UserControlTextArea.ascx is defined below:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControlTextArea.ascx.cs"  Inherits="stuff....UserControlTextArea" %>

<script type="text/jscript" language="javascript">
    $(document).ready(function () {
        var counterLabel = $('#<%=lblCounter.ClientID %>');
        var textArea = $('#<%=tbTextArea.ClientID %>');
        var maxNumber = parseInt('<%=txtMaxCharacters.Value%>');
        FieldCounter(textArea, counterLabel, maxNumber);

        $(textArea).keyup(function () {
            CheckFieldLength($(textArea), maxNumber);
            FieldCounter(textArea, $(counterLabel), maxNumber);
        });
    });
</script>
<div id="OuterContainer" runat="server">
    <asp:TextBox ID="tbTextArea" runat="server" TextMode="MultiLine" Width="100%"></asp:TextBox>
    <span class="fieldLengthCounter">
        characters left: 
        <asp:Label ID="lblCounter" runat="server"></asp:Label>
    </span>
    <input type="hidden" runat="server" id="txtMaxCharacters" />
</div>

Solution

  • Your question is unclear, but definitely its a UserControl and not a ASP.Net Textbox. So you can disable the textbox inside your UC like this:-

    Approach 1 (Preferred):

    Add a public property in your UserControl code-behind:-

    public bool DisableMyTextbox
    {
       set { tbTextArea.Enabled = value; }
    }
    

    Then you can simply use this property to disable your textbox in Webform:-

    UserControlTextArea.DisableMyTextbox = false; //or true to enable back.

    Approach 2:

    Find your textbox in UserControl class and then disable it:-

    TextBox txt1 = (TextBox)SimpleUserControl1.FindControl("tbTextArea");
    txt1.Enabled = false;