Ruan
Ruan

Reputation: 4303

If statement in Asp.net Control

How would you add a "if" statement inside an ASP.NET control?

  <asp:Label ID="lblBeginDate" runat="server" Text='<%# ((DateTime)Eval("beginDate")).ToShortDateString() %>'></asp:Label>

If Date is Null set Text to "No Date Selected"

I've tried this but can't get it to work.

   <asp:Label ID="lblBeginDate" runat="server" Text='<%# ((DateTime)Eval("beginDate")) != null ? ((DateTime)Eval("beginDate")).ToShortDateString() : "No Date Selected" %>'></asp:Label>

--Error I get with my above statement "Specified cast is not valid."

Using Gridview with a dataset as a datasouce that has been populated from a SQL Database.

UPDATE -- Found what I Wanted to do. Ref

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <%if (i == 1) { %>
                <asp:Label ID="Label1" runat="server" Text="If Bloc"></asp:Label><br />
                <%} %>
                <%else { %>
                <asp:Label ID="Label2" runat="server" Text="Else Block"></asp:Label>
                <%} %>
            </div>
        </form>
    </body>
    </html>

OR

   <asp:Label ID="lblBeginDate1" runat="server" Text='<%# Eval("beginDate").ToString().Length > 0 ? ((DateTime)Eval("beginDate")).ToShortDateString():"Not Selected Yet" %>' />

Upvotes: 2

Views: 4711

Answers (2)

7alhashmi
7alhashmi

Reputation: 924

Try this:

  <asp:Label ID="lblBeginDate" runat="server" Text='<%# iif(to_char(((DateTime)Eval
  ("beginDate")).ToShortDateString()) is DBNull.Value, "No Date Selected", 
  DateTime)Eval("beginDate")).ToShortDateString() %>'></asp:Label>

Upvotes: 1

RemarkLima
RemarkLima

Reputation: 12047

Is there anything stopping you from doing this in code behind?

<asp:Label ID="lblBeginDate" runat="server" />

Then in code behind of this .aspx file:

C#

// Only cast "beginDate" to DateTime if it's not null
lblBeginDate.Text = beginDate != null ? ((DateTime)Eval("beginDate")).ToShortDateString() : "No Date Selected";

And you can continue the logic as needed much easier in code behind.

Upvotes: 1

Related Questions