1

I have a DataGridView with ASP.net hyperlink fields inside of it. What I'm trying to do is not display a certain hyperlink based on a condition. I have SQL that determines if the hyperlink should be hidden or not, but I'm having trouble getting this to work in the hyperlinks.

I tried <asp:HyperLinkField....Visible="<%= Eval(Condition) %>" /> where Condition is True or False from my SQL query.

Which of course throws the error Cannot create an object of type 'System.Boolean' from its string representation '<%= Eval(Condition)%>' for the 'Visible' property.

So I understand this from Why will <%= %> expressions as property values on a server-controls lead to a compile errors? and other similar questions.

My question now is: what is the workaround? How can I get the hyperlink to display or not based on my condition?

Community
  • 1
  • 1
MAW74656
  • 3,449
  • 21
  • 71
  • 118

2 Answers2

1

My recommendation would be to handle it in the codebehind, most likely handling the RowCreated event, and setting the Visible property of the control there. There might be more context to your application that I'm missing, but that seems like the simplest way.

This is the event: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcreated(v=vs.110).aspx

Other events on the gridview in case that one doesn't meet your needs: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview_events%28v=vs.110%29.aspx

NinjaMid76
  • 169
  • 8
1

You cannot change HyperLinkField's Visible on runtime, because it does not have a DataBinding event.

Instead, you should not be changing HyperLinkField's Visible value. The problem is the rest of the column will not be aligned properly if you hide a single cell.

enter image description here

Instead, you want to use TemplateField and HyperLink, and hide a link only (leave the table cell by itself). For example,

<asp:TemplateField>
    <ItemTemplate>
        <asp:HyperLink ID="ConditionHyperLink" runat="server" 
            Visible='<%# Convert.ToBoolean(Eval("Condition")) %>'
            Text="Link" />
    </ItemTemplate>
</asp:TemplateField>

FYI: Your syntax is not correct; it should be ='<%# Eval("") %>'

Win
  • 61,100
  • 13
  • 102
  • 181
  • -The column alignment issue isn't going to matter here, but only because its only last column I'm showing/hiding (so definately more maintainable your way. I guess I'm foggy on the difference between `<%# %>` and `<%= %>`. – MAW74656 Feb 20 '15 at 16:08