Barry Doyle Barry Doyle - 3 months ago 17
ASP.NET (C#) Question

Using Eval Boolean to set a style for an asp.net control

I have an

asp:ListView
control containing a bunch of images set up like this:

<asp:ListView ID="lvSliderPhotos" runat="server">
<ItemTemplate>
<asp:Image ID="imgSliderPhoto" runat="server"
ImageUrl='<%# Eval("ThumbnailPath") %>' />
</ItemTemplate>
</asp:ListView>


For my DB table containing these I have a field called
IsPublic
which stores a boolean. How can I apply a style to the
asp:Image
control if the value is false?

I basically want something like this:

<asp:Image ID="imgSliderPhoto" runat="server"
ImageUrl='<%# Eval("ThumbnailPath") %>'
Style='<if (!Eval("IsPublic") { set a style property }>' />


Any idea how this can be accomplished?

Answer

You can check the value of IsPublic inside the CssClass property of the image control and set it to the desired style rule:

CssClass='<%# Convert.ToBoolean(Eval("IsPublic")) ? "public" : "private" %>'

Complete example:

  <head runat="server">
    <title></title>
    <style type="text/css">
        .public {
            border: 6px solid red;
        }

        .private {
            border: 6px solid black;
        }
    </style>
</head>
<body>
    <asp:Image ID="Image1" runat="server" />
    <form id="form1" runat="server">
        <asp:ListView ID="lvSliderPhotos" runat="server">
            <ItemTemplate>
                <asp:Image ID="imgSliderPhoto" runat="server"
                    ImageUrl='<%# Eval("ThumbnailPath") %>' CssClass='<%# Convert.ToBoolean(Eval("IsPublic")) ? "public" : "private" %>' />
            </ItemTemplate>
        </asp:ListView>
    </form>
</body>