views:

454

answers:

3

The setup: Web form with lots of TextBox controls.

When I set any one of the TextBox control's Enabled property to False, I'd like to "swap" that TextBox out for a label at runtime. The idea here being if it's read only anyway, don't display it in a control designed for editing.

I'm thinking this should be pretty simple and reusable, but what's the best way to do this?

+2  A: 

One possible solution would be to create a new control extending TextBox. Your specialized control would then override (parts of) the rendering code, causing the control to render similar to a Label when ReadOnly = true.

Jørn Schou-Rode
i like they way you think...
BigBlondeViking
+3  A: 

Not sure its the best way, I would make a custom server control is a textbox,

then override the render method, check if it is readonly,

if it is read only then render your span tags like a label controls does.

if not then let the base( textbox ) render take over...

public class SpecialTextbox : TextBox
{
    public override void RenderControl(HtmlTextWriter writer)
    {
        if (!this.ReadOnly)
        {
            base.RenderControl(writer);
        }
        else
        {
            writer.Write(string.Format("<span id=\"{0}\" class=\"{1}\">{2}</span>", 
                            this.ClientID, 
                            this.CssClass, 
                            this.Text));
        }
    }
}
BigBlondeViking
you could swap 'span' for for 'label' if you want as well
BigBlondeViking
+2  A: 

Another way would be to look into using a control adapter. You would essentially be able to do the exact same thing that BigBlondeViking reccomends, but you could coninue to use a regular asp:textbox control in your code. That will be much easier on you and other developers.

About control adapters

smercer