Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 308
Slider345 Avatar asked Apr 15 '11 12:04

Slider345


2 Answers

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.

like image 73
Thorsten Dittmar Avatar answered Sep 18 '22 17:09

Thorsten Dittmar


This should work:

<a <%# String.IsNullOrEmpty(EMail) ? String.Empty : "href=mailto:Eval('Email')" %> ><%# Eval("Name") %></a>
like image 44
Akram Shahda Avatar answered Sep 20 '22 17:09

Akram Shahda