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 users of this list have emails stored in the system, which means that Eval ("Email") sometimes returns empty. When this happens, I do not want to have a link to the field, since mailto will not work without an email address.

How can i do this? I was hoping I could use the IF statement in the view code, for example, how classic ASP worked. If not, I suggest that I could create a property on my data source that includes all the href html ...

+9
source share
5 answers

Instead of Eval you can use any given public function. Therefore, you can try to 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 you have not tried the exact syntax, but I use something similar on one of my pages.

+14
source

This should work:

 <a <%# String.IsNullOrEmpty(EMail) ? String.Empty : "href=mailto:Eval('Email')" %> ><%# Eval("Name") %></a> 
+2
source
 <ItemTemplate> <%# Eval("Type").ToString() == "2" ? "Page" : "Blog" %> </ItemTemplate> 
0
source

You can use the OnRowDataBound event or, if you want, you can use the global var since Binding is sequential

like this

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

and in the form of a grid

 <%# 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
source

C # .NET use the code below

 <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 code below

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

0
source

All Articles