开发者

Can I use an IF statement in a GridView ItemTemplate?

I have a simple gridview ItemTemplate that looks like this:

<asp:TemplateField HeaderText="User">
   <ItemTemplate>
      <a href="mailto:<%# Eval("Email") %>"><%# Eval("Name") %></a>
   </ItemTemplate>
</asp:TemplateField>

However, not all of the users on this list have emails stored in the system, which means Eval("Email") sometimes returns blank. When this happens, I'd rather not have a link on the field, since the mailto won't work without an email address.

How can I do this?开发者_如何转开发 I was hoping I could use an IF statement in the presentation code kind of like how classic ASP used to work. If not, I suppose I could create a property on my datasource that includes the entire HREF html...


Instead of Eval you can use any given public function. So you might try and do something like the following:

<ItemTemplate>
    <%# (String.IsNullOrEmpty(Eval("Email").ToString()) ? String.Empty : String.Format("<a href='mailto:{0}'>{1}</a>", Eval("Email"), Eval("Name")) %>
</ItemTemplate>

If have not tried the exact syntax, but I'm using something like that in one of my pages.


C#.NET use the below code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="50" />
    <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
    <asp:TemplateField HeaderText="Status" ItemStyle-Width="100">
        <ItemTemplate>
            <asp:Label Text='<%# Eval("Status").ToString() == "A" ? "Absent" : "Present" %>'
                runat="server" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

VB.NET use the below code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="50" />
    <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
    <asp:TemplateField HeaderText="Status" ItemStyle-Width="100">
        <ItemTemplate>
            <asp:Label Text='<%# If(Eval("Status").ToString() = "A", "Absent", "Present") %>'
                runat="server" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>


This should work:

<a <%# String.IsNullOrEmpty(EMail) ? String.Empty : "href=mailto:Eval('Email')" %> ><%# Eval("Name") %></a>


<ItemTemplate>
    <%# Eval("Type").ToString() == "2" ? "Page" : "Blog" %>
</ItemTemplate>


You can use event OnRowDataBound or if you prefer can use a global var because Binding is sequencial

like this

public int myvar;

public void SetMyVar(int i) {
    myvar = i
}

and in grid view

<%# SetMyVar(DataBinder.Eval(Container.DataItem, "Day")) %>
<% if (myvar == 0) { %>
      <%# Eval("Day") %>
<% } else { %>
     <asp:HyperLink ID="hplDay" runat="server" NavigateUrl="" Target="_blank" Text='<%# Eval("Day") %>' />                                
<% } %>   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜