Friday, January 22, 2016

C# GridView - Hide Cell/Link When Value is NULL

By default, I could not get GridView to hide hyperlink (HyperLinkField) when the tag value is null. I tried searching for a way to get around this and did not find a simple solution.

First, the solution that I decided to do was just to update my query to provide the text when there is a value and an empty string if the value is null. I do this using a CASE...WHEN...END in my sql query.

For example:
SELECT *, newcolumn = CASE WHEN column IS NULL THEN '' ELSE 'text' END FROM table

In the gridview, I set gridview's DataTextField = newcolumn.

For example:
<asp:HyperLinkField DataNavigateUrlFields="columnid" DataNavigateUrlFormatString="http://www.dlastlee.com/?id={0}" HeaderText="column" DataTextField="newcolumn" />

Another method from what I found was to use an ItemTemplate. http://forums.asp.net/t/1210815.aspx?Conditional+Logic+on+HyperlinkField


For some reason, this was actually very difficult to find. I wonder if I am doing something incorrectly. I couldn't possibly be the only person to want to do this. Everyone seems to want to hide a column.


I used this logic for list of movies that links to other sites:
http://dlastlee.com/Apps/Generic/FilmographyMovies.aspx


No comments:

Post a Comment