0

I'm new to ASP.NET, and I'm trying to figure out how to only show a chunk of code in the .aspx file if a value is not null or whitespace. Here's what I have, within a DetailsView:

<asp:TemplateField HeaderText="Phone">
    <EditItemTemplate>
        <asp:TextBox runat="server" ID="txtPhone" Text='<%# Bind("Phone") %>'></asp:TextBox>
    </EditItemTemplate>
    <ItemTemplate>
        <a href="tel:<%# Eval("Phone") %>">
            <i class="icon-phone"></i>
            <%# Eval("Phone") %>
        </a>
    </ItemTemplate>
</asp:TemplateField>

I want to conditionally hide the whole a tag if Eval("Phone") is null or whitespace. I would prefer to do this all in the markup, as opposed to doing something in the code-behind.

Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222

3 Answers3

1

David's answer pointed me in the right direction:

<asp:HyperLink runat="server" NavigateUrl='tel:<%# Eval("Phone") %>'
        Visible='<%# !string.IsNullOrWhiteSpace(Eval("Phone").ToString()) %>'>
    <i class="icon-phone"></i>
    <%# Eval("Phone") %>
</asp:HyperLink>
Community
  • 1
  • 1
Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222
0

First, change it to an ASP:Hyperlink control. The html A tag doesn't have a nive convenient Visible property like the ASP:Hyperlink control does.

Then you can set the visibility declaratively.

<asp:HyperLink runat="Server" NavigateUrl='tel:<%# Eval("Phone") %>' Text='<%# Bind("Phone") %>' Visible = '<%= DataBinder.Eval(Container.DataItem("phone").ToString().Trim() == "" %>' />
David
  • 72,686
  • 18
  • 132
  • 173
  • What should `Container` be? Is that some existing property that should exist, or should I replace that with something else? The `ID` of my `DetailsView` is `dvOrg`, but trying to do `dvOrg.DataItem("Phone")` has an error "Method, delegate or event is expected". – Sarah Vessels Jun 14 '12 at 21:33
  • Container.DataItem is just there as long as you're within a databound control like a Repeater, FormView, DetailsView, etc. Documentation here: http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx – David Jun 14 '12 at 21:35
  • `Container` didn't seem to exist, VS wanted to import some `Container` class from `System.ComponentModel` into the .aspx. – Sarah Vessels Jun 14 '12 at 21:36
0

I am afraid you can't do the conditional if within an eval statement. Instead, just wrap the simple eval with the function but To handle this situation i usually add a method called NullHandler(). Consider the function below.

protected string NullHandler()(object gridViewObject)
   {
        if (object.ReferenceEquals(gridViewObject, DBNull.Value))
      {
            return "Empty";
       }
        else
       {
            return gridViewObject.ToString();
      }
    }

then you can put like below

<asp:Label ID=”phoneLbl” runat=”server” Text=’<%# NullHandler(Eval(“Phone”)) %>’>

Hope this help.

MMK
  • 3,673
  • 1
  • 22
  • 30