Creating a optional LinkButton in an ASP.NET DataGrid
Something I ran into the other day: We needed a Grid with some of the cells data containing a link. However, a standard linkbutton column would not do the trick, as the data could some times be null, sometimes just data (no link) and sometimes the whole link.
The empty cells were a problem too, because the empty A tags that got rendered were redundant, and messed up the look and feel.
I ended up using the following solution:
- Create a LinkButton column as normal
- Subscribe to the ItemDataBound event and perform some filtering.
The filtering works as follows: In the ItemDataBound event, get the Item.Controls and lookup the correct column (sadly, this is on index). Then evaluate your data. In case it needs a link, do nothing. In case it does not need a link, but contains data, clear the Controls collection and create your own Literal control, put the data in and add to the controls collection of the cell. When the data is empty, perform the same actions, but put in the literal control, so the grid will still look good.