2009-09-18

Difference between Eval and Bind databinding expressions

Hi. I just faced a problem where I was using an ASP.NET GridView control which was bound to a SqlDataSource. One of the bound columns was “User” and, of course, brought the user name. What I wanted to do was to add a HyperLink to that text, so that instead of just saying “Mark”, with would show up as a link to the UserDetalis page, passing “Mark” as a QueryString variable. Something like this:

  1: <a href='UserDetails.aspx?user=Mark>Mark</a>

So, because I had a databound GridView, I just had to make the “User” column a template column and replace the standard label (Label1 in this code)

  1: <asp:GridView ID="myGridView" runat="server" 
  2:     DataSourceID="myDataSource">
  3:     <Columns>
  4:         <asp:TemplateField HeaderText="User" SortExpression="User">
  5:             <ItemTemplate>
  6:                 <asp:Label ID="Label1" runat="server" Text='<%# Bind("User") %>' />
  7:             </ItemTemplate>
  8:         </asp:TemplateField>
  9:     </Columns>
 10: </asp:GridView>

by a HyperLink (HyperLink1 in this code), and set its NavigateUrl property to the new value, which held the whole hyperlink HTML text. So the first thing that came to my mind was to do something like this:

  1: <asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Bind("User") %>'
  2:     NavigateUrl='<%# String.Format("UserDetails.aspx?user={0}", Bind("User")) %>' />

But it turned out I got a runtime error that said: The name 'Bind' does not exist in the current context. If I used Eval instead of Bind:

  1: <asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("User") %>'
  2:     NavigateUrl='<%# String.Format("UserDetails.aspx?user={0}", Eval("User")) %>' />

It worked like a charm.

OK, I got my problem solved, but now I needed to know the difference between both, and specifically why it worked with one and not the other. Well, here it is:

Eval is one way, for read-only purposes, as Bind is two way, for read-write operations. Eval is actually a static protected method defined on the TemplateControl class, from which the Page class is derived, and it returns a string. Because it’s a real method, you could combine it with other statements, like the string.Format we just used. Bind, on the other hand, is not an actual method, it’s a new ASP.NET 2.0 databinding keyword, so of course, it can’t be used with other method calls or stuff. Bottom line is, if you need to only read the text, and perhaps change it a little, use Eval. If you need to write back to the db or something like that, use Bind.

Hope you got it clear. This article has some more deep definitions, which you might find useful as well.

No hay comentarios:

Publicar un comentario

Your tips and thoughts are always welcome, and they provide good motivation: