The premise for this is quite straightforward, I’m using an ASP.NET Repeater control to display the results of a query – one row per item. As an example I’m going to display a list of students and a Checkbox IFF the data allows. To do that I need to create a function in the code behind and then pass my arguments to it from within my repeater.
Unfortunately Repeater controls do not allow you to embed <% if … %> statements, otherwise I could do something like this:
<% If String.IsNullOrEmpty(Eval("SelectText")) Then%>
<td class="chkColumn"><asp:CheckBox ID="chk" runat="server" /></td>
<% End If %>
Using this approach will result in an error: “Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.” Annoyingly it isn’t valid to use this kind of logic in the repeater, despite the fact that Visual Studio helped me write it by providing me with intellisense.
To get around that I moved the logic to a function in the code behind. This has a few advantages, the logic can be a lot more complicated and it keeps the aspx file a bit cleaner / free from the logic. This is how I’m doing it now:
<asp:CheckBox ID="chk" runat="server" Visible='<%# ShouldShowIf(False, Eval("SelectText")) %>' />
<asp:Literal ID="ltSelectText" runat="server" Text='<%#Eval("SelectText")%>'
Visible='<%# ShouldShowIf(True, Eval("SelectText")) %>' /></td>
The function ShouldShowIf is declared in the code behind for this page:
Public Shared Function ShouldShowIf(ByVal returnBool As Boolean, ByVal value As String) As String
Return If(value.Length > 0, returnBool, Not returnBool)
ShouldShowIf takes 2 arguments, the value to evaluate and the flavour of the Boolean to return. I needed to allow the calling code to determine whether it should return True or False because the checkbox should be shown if the SelectText is empty otherwise it should display the SelectText value.
I’ve used this approach before, but forgot about it – so I’m posting it up in the hopes that it helps someone else, if nothing else it will serve to remind me how to do this in future.
| Categories: ASP.NET | Development | Tips&Tricks