0

I wonder if there is any way to do this:

<asp:Label ID="lblSomething" runat="server" Visible="this.ShowLabel"/>

and in the code behind:

public bool ShowLabel {get;set;}

I know some of you may ask me why I need it but I find this approach cleaner than saying this in the code behind:

lblSomething.Visible = this.ShowLabel

And also I could say this in source view:

<% if(this.ShowLabel){ %>
   <asp:Label ID="lblSomething" runat="server" Text="Something"/>
<% } %>

but again, the first one would be more intuitive to me. Any ideas?

2 Answers 2

2

Honestly in your case, the easiest, cleanest and most elegant solution is using Visible attribute, instead of creating other boolean and make Visible have the same value.

In the other hand, Label control isn't a sealed class. If you need to do such things, I'd find better derive Label and implement ShowLabel property this way:

private bool _showLabel;

public bool ShowLabel
{
    get { return _showLabel; }
    set
    {
        _showLabel = value;
        Visible = value
    }
}

Finally, your new MyLabel control usage would be:

<gray:MyLabel ID="lblSomething" runat="server" ShowLabel="true"/>

Anyway, and again, if you're hidding such control using Visible, don't reinvent the wheel: use what comes from ASP.NET. However, if your question shows a sample but real-world scenario isn't Visible but other things, I'd argue that you should use inheritance (this is more elegant than your proposal).

In fact, a good ASP.NET Web Forms practice is completely separate markup from presentation logic.

Sign up to request clarification or add additional context in comments.

Comments

2

If your ShowLabel property is really just a wrapper around the visibility property of the label, you can just replace your property definition with:

public bool ShowLabel
{
    get { return lblSomething.Visible; }
    set { lblSomething.Visible = value; }
}

But that doesn't really give you much other than a new name for the visibility property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.