【问题标题】:How do I run an if statement in aspx?如何在 aspx 中运行 if 语句?
【发布时间】:2011-04-26 00:12:58
【问题描述】:

我想运行一个 if 语句,但条件使用了后面代码中的一个变量。我怎么称呼那个变量? 旁注...我正在使用 gridview 并且变量在数据集中(dsResult - idnbr 列)

<ItemTemplate>                        
   <% string temp = (Eval("idnbr").ToString());
   if (temp.Contains("X")) { %>
       <asp:Label ID="Label1" runat="server" Text='<%# (Eval("old_amt").ToString(),"ccTot") %>'></asp:Label>
   <% } else { %>
       <asp:Label ID="Label2" runat="server" Text='<%# (Eval("new_amt").ToString(),"ccTot") %>'></asp:Label>
   <% } %>
</ItemTemplate>

【问题讨论】:

    标签: c# .net asp.net html gridview


    【解决方案1】:

    创建为您执行此操作的 c# 端方法: 比使用以下两种方式之一:

    • 如果你处理众所周知的实体(比如当 GridView 绑定到 ObjectDatasource 时)你 可以将其投射到您的实体并传回:

    C#:

     protected String MySelectorImpl(Object rowData)
     {
         MyEntity ent = (MyEntity)rowData;
         if(ent.idndr .... ) 
            return ....
         else 
            return ...
     }
    

    ASP.Net:

    <ItemTemplate>
        <asp:Label Text='<%# MySelector(Container.DatatItem) %>' ...
    

    第二种情况 - 只使用 eval 语法

    C#:

    protected string MySelector(Object condition, Object value1, Object value2)
    {
        if((String)condition ....) return value1.ToString ....
    }
    

    ASP.Net:

    <ItemTemplate>
        <asp:Label Text='<%# MySelector(Container.DatatItem("idnbr", ... %>' ...
    

    (,

    【讨论】:

      【解决方案2】:

      我知道这并不能完全回答您的问题,但为什么不在后面的代码中这样做呢?我假设您正在使用 DataBinding 做某事?

      string temp  = (string)DataBinder.Eval(e.Item.DataItem, "idnbr");
      string newAmount = (string)DataBinder.Eval(e.Item.DataItem, "new_amt");
      string oldAmount = (string)DataBinder.Eval(e.Item.DataItem, "old_amt");
      Label lbl1        = e.Item.FindControl("label1") as Label;
      
      if(temp.Contains("X") {
       lbl1.Text = oldAmount;
      } else {
       lbl1.Text = newAmount;
      }
      

      【讨论】:

        【解决方案3】:

        您可以从后面代码中声明的属性中读取;这满足你想要的吗?

        您可以使用this.MyProperty.Contains("X")...代替string temp =...

        【讨论】:

        • 只需要确保它是可见的(公共的或受保护的)
        • @David Right...我的意思是当我说财产时,但我想我应该明确:-)
        【解决方案4】:
        <a href="javascript:onclick= window.location = 'RenewalPaymentGateway.aspx?RPID=<%# Eval("RPID")%>'" title="Pay">
         <asp:Label ID="TEMP" Text='<%# If(Eval("PaymentStatus").ToString() = "Paid", "View", "Make payment") %>'  runat="server" />
        

        here in label the text view will appear when PaymentStatus=paid or the text will be make payment
        

        【讨论】:

          猜你喜欢
          • 2017-12-22
          • 2013-05-24
          • 2011-03-05
          • 2022-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-26
          • 1970-01-01
          相关资源
          最近更新 更多