Tuesday, October 23, 2012

Asp.net Eval() and Bind() expressions in data bound controls like GridView and DetailsView


The asp.net Eval() and Bind() expressions are heavily used in asp.net GridView and DetailsView data bound controls. The difference between these two is that Eval is used for read only purpose and Bind is used for read/edit purpose. For example Eval can be used to bind the Text property of an asp.net Label control whereas Bind can be used to bind the asp.net TextBox control so that it can be edited to meet some requirement. Of course, asp.net GridView and DetailsView controls make large use of these Eval and Bind expressions. And I have put some cases here.

I have already talked about the DataFormatString in asp.net GridView and DetailsView controls when using Eval expression. You can take these two examples and customize these expressions as your requirement demands.


  1. <asp:DetailsView Width="100%" ID="dvwCategory" runat="server" AutoGenerateRows="False" HeaderText="Product Category Details">      
  2.   
  3.         <FieldHeaderStyle Width="10%" />  
  4.   
  5.         <Fields>  
  6.   
  7.             <asp:BoundField DataField="Category_ID" HeaderText="ID" InsertVisible="false" ReadOnly="true"/>  
  8.   
  9.             <asp:TemplateField HeaderText="Category Name">    
  10.   
  11.                 <ItemTemplate>  
  12.   
  13.                     <asp:Label ID="lblCategoryName" runat="server" Text='<%# Eval("Category_Name") %>'></asp:Label>  
  14.   
  15.                 </ItemTemplate>  
  16.   
  17.                 <EditItemTemplate>  
  18.   
  19.                     <asp:TextBox ID="txtCategoryName" runat="server" Text='<%# Bind("Category_Name") %>'></asp:TextBox>  
  20.   
  21.                 </EditItemTemplate>  
  22.   
  23.             </asp:TemplateField>  
  24.   
  25.             <asp:CheckBoxField DataField="Active" HeaderText="Active"/>  
  26.   
  27.         </Fields>  
  28.   
  29.     </asp:DetailsView>  


Then why use Eval and Bind since the BoundField can has DataField property (like DataField="Category_ID")? Yeah, it's mostly useful when we have no other choices but templatefileds in asp.net gridview and detailsview controls. We can format the date and currency in various formats, and so on. But most important is it provides us much flexibility in playing between the nature of asp.net GridView and DetailsView controls and an asp.net programmer's requirement. You can share yourself by commenting this post. You are heartily requested to share this post by bookmarking this post (You can just add by clicking in the social bookmak buttons just below this post! It's that easy! Thanks for your interest and support). Happy programming!