The following is Fritz Onion’s posting on Complex data binding expressions in ASP.NET, converted into VB.NET:
I often find when using templated data-bound controls (in either ASP.NET 1.1 or 2.0) that my expressions become rather difficult to understand because of the need to fit all of your logic into a single expression. For example, I have seen databound expressions that look something like:
<asp:TemplateField HeaderText="SomeColumn"> <ItemTemplate> <%# ((bool)Eval("foo")) ? Eval("bar") : (((bool)Eval("quux")) ? Eval("a") : Eval("b")) %> </ItemTemplate></asp:TemplateField>
Which is even worse in 1.1 because each Eval must be replaced with DataBinder.Eval(Container.DataItem, "xx"). There are also occasions where you just can't compress all the logic you need to into a single expression. An alternative, which I find myself using quite a bit, even when developing in 2.0, is to write a single method in your code behind class to generate the desired string. Have it take an object reference (which will be the bound row) and take as many lines as you like to construct the string to be generated in the template. Here's a method that returns the same string as the overly-complex expression above:
Protected Function GenerateFooString(ByVal dataItem As Object) As String Dim foo As Boolean = CType(DataBinder.Eval(dataItem, "foo"),Boolean) Dim quux As Boolean = CType(DataBinder.Eval(dataItem, "quux"),Boolean) Dim ret As String = string.Empty If foo Then ret = CType(DataBinder.Eval(dataItem, "bar"),String) ElseIf quux Then ret = CType(DataBinder.Eval(dataItem, "a"),String) Else ret = CType(DataBinder.Eval(dataItem, "b"),String) End If Return retEnd Function
And the simplified template now looks like:
<asp:TemplateField HeaderText="SomeColumn"> <ItemTemplate> <%# GenerateFooString(Container.DataItem) %> </ItemTemplate></asp:TemplateField>
Once again, this is not my code or idea; it all belongs to Fritz Onion!