C# – use an IF statement in a GridView ItemTemplate

asp.netc++data-bindinggridview

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…

Best Solution

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.