如果在Asp.net控件中声明

时间:2013-04-30 09:00:36

标签: asp.net if-statement controls

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

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

如果Date为Null,则将Text设置为“No Date Selected”

我已经尝试过了,但无法让它发挥作用。

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

- 我在上面的陈述中得到错误“指定的演员表无效。”

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

更新 - 找到我想做的事。 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" %>' />

2 个答案:

答案 0 :(得分: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";

您可以在后面的代码中更轻松地继续使用逻辑。

答案 1 :(得分: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>