Saturday, December 17, 2005 9:48:14 PM UTC :: Filed Under ASP.NET

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 ObjectAs 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 
ret
End 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!

Thursday, May 31, 2007 1:29:01 AM UTC
Useful usage on databinder.eval method, http://dotnetguts.blogspot.com/2006/12/databindereval-method.html
Comments are closed.
Navigation
On this page....
Search
Archives
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Categories
Contact me
Send mail to the author(s) Contact Todd M. Taylor