1

如何在 ASP.NET 控件中添加“if”语句?

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

如果日期为空,则将文本设置为“未选择日期”

我已经尝试过了,但无法让它工作。

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

--错误我的上述声明“指定的演员表无效。”

将 Gridview 与数据集一起用作从 SQL 数据库填充的数据源。

更新——找到我想做的事。参考

    <%@ 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>

或者

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

2 回答 2

1

有什么东西阻止你在后面的代码中这样做吗?

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

然后在这个 .aspx 文件后面的代码中:

C#

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

您可以在后面的代码中更轻松地根据需要继续执行逻辑。

于 2013-04-30T09:11:37.857 回答
1

尝试这个:

  <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>
于 2013-04-30T09:18:16.587 回答