Search code examples
c#asp.net-3.5custom-server-controls

Why is the Enabled property of a custom CompositeControl still setting disabled="disabled" when the property is overridden?


I have created a custom server control that inherits from CompositeControl. In the CreateChildControls method, I add an input and a label control (there are others, too) to the control tree. I have overridden the Enabled property so that I only get/set the input's Enabled property, not the composite control's Enabled property. In the user control where I use this server control, I add Enabled="false" to the markup. However, no matter what I do, the container div gets a disabled="disabled" attribute added to it (and so do some of the children).

Of course, this seems to work just fine in all browsers except IE 6. If there's a fieldset legend or a radio button list inside the disabled control, the text disappears. I was originally trying to see if there was some defect to fix via CSS for IE 6. Then, I noticed the disabled="disabled" on tags I didn't even think were valid to have that attribute.

What exactly am I doing wrong here?

Sample control that exhibits behavior:

public class TextBoxWithLabel : CompositeControl
{
    private readonly Label _label = new Label();
    private readonly TextBox _textBox = new TextBox();

    protected override HtmlTextWriterTag TagKey
    {
        get { return HtmlTextWriterTag.Div; }
    }

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

    public override bool Enabled
    {
        get { return _textBox.Enabled; }
        set { _textBox.Enabled = value; }
    }

    protected override void CreateChildControls()
    {
        _label.ID = ID + "_label";
        _textBox.ID = ID + "_field";
        _label.AssociatedControlID = _label.ID;

        Controls.Add(_label);
        Controls.Add(_textBox);
    }
}

Usage:

<test:TextBoxWithLabel id="tester" runat="server" LabelText="My TextBox" Enabled="false" />

Solution

  • I have solved this by creating a "new" Enabled property instead of overriding.

    public new bool Enabled
    {
        get { return _textBox.Enabled; }
        set { _textBox.Enabled = value; }
    }
    

    I won't accept this answer unless I get up-votes from others verifying my finding for the need to do this.