Eval vs Bind for ASP.NET

Written by Alex on . Posted in Uncategorized

When you start working with ASP.NET sometimes it’s difficult to understand what is the difference between Eval and Bind for data binding controls in ASP.NET. If you just need to display data on the screen from DataSource it’s enough to use Eval. It’s something like read-only method from DataSource. But if you need to edit data inside of Grid you have to use Bind method. Because it provides two way binding you can read data from DataSource and you can write data back. Usually you have to use this methods if you need to quickly develop some WebPages and display and edit data from one table or simple view. If you try to edit some row in Data Grid and want to make some changes in code behind class in OnUdpdating event, data with Eval method will not be available instead of Bind method.

<asp:GridView ID="GridView1" runat="server" CssClass="dataGrid"
   DataSourceID="SqlDataSource1" AllowPaging="True" AutoGenerateColumns="false"
  OnRowDeleting="grid_onRowDeleting" OnRowUpdating="GridView1_OnRowUpdating"
    AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
  PageSize="20" GridLines="None" Width="99%">
   <AlternatingRowStyle CssClass="odd" />
   <Columns>

       <asp:TemplateField HeaderText="App Id">
           <ItemTemplate>
               <asp:Label ID="lbl" runat="server" Text='<%#Bind("APP_ID") %>'></asp:Label>
           </ItemTemplate>
       </asp:TemplateField>

      <asp:TemplateField HeaderText="App name">
           <ItemTemplate>
               <%#Eval("APPLICATION_NAME")%>
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>
protected void GridView1_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
   // if APP_ID in the grid bind with Eval method, it will be exception below
   // But if you use Bind instead of Eval it will be ok.
   rowToUpdate = e.NewValues["APP_ID"];
}

Tags: ,

Trackback from your site.

Leave a comment