arinte
arinte

Reputation: 3728

Conditional render in asp.net

How can I get something like this to work in asp.net

<asp:Panel Visible="<%(SType==switch_type.Trunk).ToString()%>" runat="server">Tickle</asp:Panel>

Where switch_type is an enum of values and SType is a get/set in the codebehind.

I have this working, but I just feel it is ugly

<% if (SType == switch_type.Trunk)
    { %>
        ...

I know I can set the panel as visible/invisible in the codebehind, but there are going to be a lot of panels and it just seems easier to set the visibility in the aspx file.

Upvotes: 1

Views: 3286

Answers (4)

Stephen Wrighton
Stephen Wrighton

Reputation: 37819

Behold, the power of Events!

ASPX side:

<asp:panel runat="server" id="myPnlName OnLoad="panelLoadEvent" Tooltip='<% Response.Write(switch_type.Trunk) %>'>
    Stuff
</asp:panel>

Code Side:

protected sub panelLoadEvent(sender as object, e as EventArgs)
  dim pnl as Panel = sender 
  dim oItem as switch_type = ctype(pnl.ToolTip, switch_type) 
  pnl.visibile = iif(stype=oItem,true,false)
End sub 

The point is you put the VALUE you want to check into the tooltip of the panel, and every panel gets processed by the same LoadEvent handler as defined in the OnLoad attribute of the Panel aspx declaration.
At that point you check to see if the given value matches your variable, and set the visibility appropriately.

EDIT If you want to store a string representation in the tooltip as opposed to the underlying int of the enum, you can parse it back to the enum using something like:

[Enum].Parse(System.Type, Value)

Upvotes: 2

Robin Day
Robin Day

Reputation: 102478

As there's a lot of panels is it worth creating a dataset that you can bind to from a Repeater and you will then be able to use the <%# %> syntax to perform your visible invisible logic?

Upvotes: 0

Jack Ryan
Jack Ryan

Reputation: 8472

How about this

<asp:Panel runat="server" Visible="<%= SType == switch_type.Trunk %>">
    Stuff
</asp:Panel>

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

You could use a MultiView control, and put each panel in one of the views.

Upvotes: -1

Related Questions