CRUD Operations Using Entity Framework in ASP.NET

Here in this application I will use an Item template, Edit Item template and Footer Template to do CRUD operations.

The following is my Data Table in design mode:

emp id
                                      Image 1.

Data in my Data Table:

My Data Table
                                                                              Image 2.

To create the new application go to Solution Explorer in your application then select Add New Item.

Add an ADO.NET Entity Data Model.

Entity Data Model
                                                                              Image 3.

generate database
                                                                        Image 4.

new connection
                                                                              Image 5.

Enter your server information and select your database:

select your Data base
                                                   Image 6.

select data connection
                                                                        Image 7.

table
                                                                             Image 8.

property
                                                                        Image 9.

Now open Default.aspx and do the following code:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CRUDUsingEntityFramework.Default" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title>CRUD Operation Using Entity Framework In ASP.NET Grid View</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.         <div>  
  10.             <table style="border: solid 15px blue; width: 100%; vertical-align: central;">  
  11.                 <tr>  
  12.                     <td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px;   
  13.                         background-color: skyblue; font-family: 'Times New Roman';   
  14.                             font-size: 20pt; color: red;">CRUD Operation Using Entity Framework In ASP.NET Grid View  
  15.                     </td>  
  16.                 </tr>  
  17.                 <tr>  
  18.                     <td style="text-align: left;">  
  19.   
  20.                         <asp:GridView ID="GVEmployee" runat="server"   
  21.                             AutoGenerateColumns="False" ShowFooter="True"   
  22.                             PageSize="10" AllowPaging="true"  
  23.                             OnRowCommand="GVEmployee_RowCommand"  
  24.                             DataKeyNames="Emp_ID" CellPadding="4" ForeColor="#333333"  
  25.                             GridLines="None" OnRowCancelingEdit="GVEmployee_RowCancelingEdit"  
  26.                             OnRowEditing="GVEmployee_RowEditing"  
  27.                             OnRowUpdating="GVEmployee_RowUpdating"  
  28.                             OnRowDeleting="GVEmployee_RowDeleting"  
  29.                             OnPageIndexChanging="GVEmployee_OnPageIndexChanging">  
  30.                             <AlternatingRowStyle BackColor="White" />  
  31.                             <Columns>  
  32.                                 <asp:TemplateField HeaderText="Employee Name" HeaderStyle-HorizontalAlign="Left">  
  33.                                     <EditItemTemplate>  
  34.                                         <asp:TextBox ID="txtEmpName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>  
  35.                                         <asp:RequiredFieldValidator ID="valEmpName" runat="server" ControlToValidate="txtEmpName"  
  36.                                             Display="Dynamic" ErrorMessage="Employee Name is required." ForeColor="Red" SetFocusOnError="True"  
  37.                                             ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator>  
  38.                                     </EditItemTemplate>  
  39.                                     <ItemTemplate>  
  40.                                         <asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>  
  41.                                     </ItemTemplate>  
  42.                                     <FooterTemplate>  
  43.                                         <asp:TextBox ID="txtEmpNameNew" runat="server"></asp:TextBox>  
  44.                                         <asp:RequiredFieldValidator ID="valEmpNameNew" runat="server" ControlToValidate="txtEmpNameNew"  
  45.                                             Display="Dynamic" ErrorMessage="Employee Name is required." ForeColor="Red" SetFocusOnError="True"  
  46.                                             ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator>  
  47.                                     </FooterTemplate>  
  48.                                 </asp:TemplateField>  
  49.                                 <asp:TemplateField HeaderText="Designation" HeaderStyle-HorizontalAlign="Left">  
  50.                                     <EditItemTemplate>  
  51.                                         <asp:TextBox ID="txtDesignation" runat="server" Text='<%# Bind("Designation") %>'></asp:TextBox>  
  52.                                         <asp:RequiredFieldValidator ID="valDesignation" runat="server" ControlToValidate="txtDesignation"  
  53.                                             Display="Dynamic" ErrorMessage="Designation is required." ForeColor="Red" SetFocusOnError="True"  
  54.                                             ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator>  
  55.                                     </EditItemTemplate>  
  56.                                     <ItemTemplate>  
  57.                                         <asp:Label ID="lblDesignation" runat="server" Text='<%# Bind("Designation") %>'></asp:Label>  
  58.                                     </ItemTemplate>  
  59.                                     <FooterTemplate>  
  60.                                         <asp:TextBox ID="txtDesignationNew" runat="server"></asp:TextBox>  
  61.                                         <asp:RequiredFieldValidator ID="valDesignationNew" runat="server" ControlToValidate="txtDesignationNew"  
  62.                                             Display="Dynamic" ErrorMessage="Designation is required." ForeColor="Red" SetFocusOnError="True"  
  63.                                             ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator>  
  64.                                     </FooterTemplate>  
  65.                                 </asp:TemplateField>  
  66.                                 <asp:TemplateField HeaderText="City" HeaderStyle-HorizontalAlign="Left">  
  67.                                     <EditItemTemplate>  
  68.                                         <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>  
  69.                                         <asp:RequiredFieldValidator ID="valCity" runat="server" ControlToValidate="txtCity"  
  70.                                             Display="Dynamic" ErrorMessage="City is required." ForeColor="Red" SetFocusOnError="True"  
  71.                                             ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator>  
  72.                                     </EditItemTemplate>  
  73.                                     <ItemTemplate>  
  74.                                         <asp:Label ID="lblCity" runat="server" Text='<%# Bind("City") %>'></asp:Label>  
  75.                                     </ItemTemplate>  
  76.                                     <FooterTemplate>  
  77.                                         <asp:TextBox ID="txtCityNew" runat="server"></asp:TextBox>  
  78.                                         <asp:RequiredFieldValidator ID="valCityNew" runat="server" ControlToValidate="txtCityNew"  
  79.                                             Display="Dynamic" ErrorMessage="City is required." ForeColor="Red" SetFocusOnError="True"  
  80.                                             ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator>  
  81.                                     </FooterTemplate>  
  82.                                 </asp:TemplateField>  
  83.                                 <asp:TemplateField HeaderText="State" HeaderStyle-HorizontalAlign="Left">  
  84.                                     <EditItemTemplate>  
  85.                                         <asp:TextBox ID="txtState" runat="server" Text='<%# Bind("State") %>'></asp:TextBox>  
  86.                                         <asp:RequiredFieldValidator ID="valState" runat="server" ControlToValidate="txtState"  
  87.                                             Display="Dynamic" ErrorMessage="State is required." ForeColor="Red" SetFocusOnError="True"  
  88.                                             ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator>  
  89.                                     </EditItemTemplate>  
  90.                                     <ItemTemplate>  
  91.                                         <asp:Label ID="lblState" runat="server" Text='<%# Bind("State") %>'></asp:Label>  
  92.                                     </ItemTemplate>  
  93.                                     <FooterTemplate>  
  94.                                         <asp:TextBox ID="txtStateNew" runat="server"></asp:TextBox>  
  95.                                         <asp:RequiredFieldValidator ID="valStateNew" runat="server" ControlToValidate="txtStateNew"  
  96.                                             Display="Dynamic" ErrorMessage="State is required." ForeColor="Red" SetFocusOnError="True"  
  97.                                             ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator>  
  98.                                     </FooterTemplate>  
  99.                                 </asp:TemplateField>  
  100.   
  101.                                 <asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">  
  102.                                     <EditItemTemplate>  
  103.                                         <asp:TextBox ID="txtCountry" runat="server" Text='<%# Bind("Country") %>'></asp:TextBox>  
  104.                                         <asp:RequiredFieldValidator ID="valCountry" runat="server" ControlToValidate="txtCountry"  
  105.                                             Display="Dynamic" ErrorMessage="Country is required." ForeColor="Red" SetFocusOnError="True"  
  106.                                             ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator>  
  107.                                     </EditItemTemplate>  
  108.   
  109.                                     <ItemTemplate>  
  110.                                         <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country") %>'></asp:Label>  
  111.                                     </ItemTemplate>  
  112.   
  113.                                     <FooterTemplate>  
  114.                                         <asp:TextBox ID="txtCountryNew" runat="server"></asp:TextBox>  
  115.                                         <asp:RequiredFieldValidator ID="valCountryNew" runat="server" ControlToValidate="txtCountryNew"  
  116.                                             Display="Dynamic" ErrorMessage="Country is required." ForeColor="Red" SetFocusOnError="True"  
  117.                                             ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator>  
  118.                                     </FooterTemplate>  
  119.                                 </asp:TemplateField>  
  120.   
  121.                                 <asp:TemplateField HeaderText="">  
  122.                                     <ItemTemplate>  
  123.                                         <asp:LinkButton ID="lnkEdit" runat="server" Text="" CommandName="Edit" ToolTip="Edit">  
  124.                                             <img src="../Images/Edit.png" width="30px" />  
  125.                                         </asp:LinkButton>  
  126.                                         <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName="Delete"  
  127.                                             ToolTip="Delete" OnClientClick='return confirm("Are you sure you want to delete employee record?");'>  
  128.                                             <img src="../Images/Delete.jpg"  width="30px" />  
  129.                                         </asp:LinkButton>  
  130.                                     </ItemTemplate>  
  131.   
  132.                                     <EditItemTemplate>  
  133.                                         <asp:LinkButton ID="lnkInsert" runat="server" Text="" ValidationGroup="vldEditRecord"   
  134.                                             CommandName="Update" ToolTip="Save"  
  135.                                             OnClientClick='return confirm("Employee Record Saved Successfully.");'>  
  136.                                                  <img src="../Images/Save2.jpg"  width="30px" />  
  137.                                         </asp:LinkButton>  
  138.                                         <asp:LinkButton ID="lnkCancel" runat="server" Text="" CommandName="Cancel" ToolTip="Cancel">  
  139.                                             <img src="../Images/Cancel.jpg"  width="30px" />  
  140.                                         </asp:LinkButton>  
  141.                                     </EditItemTemplate>  
  142.   
  143.                                     <FooterTemplate>  
  144.                                         <asp:LinkButton ID="lnkInsert" runat="server" Text="" ValidationGroup="vldNewRecord"   
  145.                                             CommandName="InsertNew" ToolTip="Add New Employee"  
  146.                                             OnClientClick='return confirm("Employee Record addedd Successfully.");'>  
  147.                                                  <img src="../Images/Insert.jpg"  width="30px" />  
  148.                                         </asp:LinkButton>  
  149.                                         <asp:LinkButton ID="lnkCancel" runat="server" Text="" CommandName="CancelNew" ToolTip="Cancel">  
  150.                                             <img src="../Images/Cancel.jpg"  width="30px" />  
  151.                                         </asp:LinkButton>  
  152.                                     </FooterTemplate>  
  153.   
  154.                                 </asp:TemplateField>  
  155.                             </Columns>  
  156.                             <EditRowStyle BackColor="#2461BF" />  
  157.                             <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  158.                             <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  159.                             <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />  
  160.                             <RowStyle BackColor="#EFF3FB" />  
  161.                             <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />  
  162.                             <SortedAscendingCellStyle BackColor="#F5F7FB" />  
  163.                             <SortedAscendingHeaderStyle BackColor="#6D95E1" />  
  164.                             <SortedDescendingCellStyle BackColor="#E9EBEF" />  
  165.                             <SortedDescendingHeaderStyle BackColor="#4870BE" />  
  166.                         </asp:GridView>  
  167.                     </td>  
  168.                 </tr>  
  169.             </table>  
  170.         </div>  
  171.     </form>  
  172. </body>  
  173. </html>  
Now my aspx.cs code is:

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. namespace CRUDUsingEntityFramework  
  9. {  
  10.     public partial class Default : System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.             if (!IsPostBack)  
  15.             {  
  16.                 BindGrid();  
  17.             }  
  18.              
  19.         }  
  20.   
  21.         void BindGrid()  
  22.         {  
  23.             using (EmployeeManagementEntities context = new EmployeeManagementEntities())  
  24.             {  
  25.                 if (context.Employee.Count() > 0)  
  26.                 {  
  27.                     GVEmployee.DataSource = (from em in context.Employee  
  28.                                              select new { em.Emp_ID, em.Name, em.Designation, em.City, em.Country, em.State }).ToList();  
  29.                     GVEmployee.DataBind();  
  30.                 }  
  31.                 else  
  32.                 {  
  33.                     GVEmployee.DataSource = null;  
  34.                     GVEmployee.DataBind();  
  35.                 }  
  36.             }  
  37.         }  
  38.   
  39.         protected void GVEmployee_OnPageIndexChanging(object sender, GridViewPageEventArgs e)  
  40.         {  
  41.             GVEmployee.PageIndex = e.NewPageIndex;  
  42.             BindGrid();  
  43.         }  
  44.   
  45.         protected void GVEmployee_RowCommand(object sender, GridViewCommandEventArgs e)  
  46.         {  
  47.             if (e.CommandName == "InsertNew")  
  48.             {  
  49.                 GridViewRow row = GVEmployee.FooterRow;  
  50.   
  51.                 TextBox txtName = row.FindControl("txtEmpNameNew"as TextBox;  
  52.                 TextBox txtDesignation = row.FindControl("txtDesignationNew"as TextBox;  
  53.                 TextBox txtCity = row.FindControl("txtCityNew"as TextBox;  
  54.                 TextBox txtState = row.FindControl("txtStateNew"as TextBox;  
  55.                 TextBox txtCountry = row.FindControl("txtCountryNew"as TextBox;  
  56.   
  57.                 using (EmployeeManagementEntities context = new EmployeeManagementEntities())  
  58.                 {  
  59.                     Employee obj = new Employee();  
  60.                     obj.Name = txtName.Text;  
  61.                     obj.Designation = txtDesignation.Text;  
  62.                     obj.City = txtCity.Text;  
  63.                     obj.State = txtState.Text;  
  64.                     obj.Country = txtCountry.Text;  
  65.                     context.Employee.Add(obj);  
  66.                     context.SaveChanges();   
  67.                     BindGrid();  
  68.                 }  
  69.   
  70.             }  
  71.         }  
  72.         protected void GVEmployee_RowEditing(object sender, GridViewEditEventArgs e)  
  73.         {  
  74.             GVEmployee.EditIndex = e.NewEditIndex;  
  75.             BindGrid();  
  76.         }  
  77.         protected void GVEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  78.         {  
  79.             GVEmployee.EditIndex = -1;  
  80.             BindGrid();  
  81.         }  
  82.         protected void GVEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  83.         {  
  84.             GridViewRow row = GVEmployee.Rows[e.RowIndex];  
  85.   
  86.             TextBox txtName = row.FindControl("txtEmpName"as TextBox;  
  87.             TextBox txtDesignation = row.FindControl("txtDesignation"as TextBox;  
  88.             TextBox txtCity = row.FindControl("txtCity"as TextBox;  
  89.             TextBox txtState = row.FindControl("txtState"as TextBox;  
  90.             TextBox txtCountry = row.FindControl("txtCountry"as TextBox;  
  91.   
  92.   
  93.             using (EmployeeManagementEntities context = new EmployeeManagementEntities())  
  94.             {  
  95.                 int employeeID = Convert.ToInt32(GVEmployee.DataKeys[e.RowIndex].Value);  
  96.                 Employee obj = context.Employee.First(x => x.Emp_ID == employeeID);  
  97.                 obj.Name = txtName.Text;  
  98.                 obj.Designation = txtDesignation.Text;  
  99.                 obj.City = txtCity.Text;  
  100.                 obj.State = txtState.Text;  
  101.                 obj.Country = txtCountry.Text;  
  102.                 context.SaveChanges();  
  103.                  
  104.                 GVEmployee.EditIndex = -1;  
  105.                 BindGrid();  
  106.             }  
  107.   
  108.         }  
  109.   
  110.         protected void GVEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  111.         {  
  112.             int employeeID = Convert.ToInt32(GVEmployee.DataKeys[e.RowIndex].Value);  
  113.             using (EmployeeManagementEntities context = new EmployeeManagementEntities())  
  114.             {  
  115.                 Employee obj = context.Employee.First(x => x.Emp_ID == employeeID);  
  116.                 context.Employee.Remove(obj);  
  117.                 context.SaveChanges();  
  118.                 BindGrid();   
  119.             }  
  120.         }  
  121.     }  
  122. }  
Now run your application: All Record

crud operation
                                                                           Image 10.

Add a new record:

record
                                                                        Image 11.

Go to Page 2 as I have Page Size 10 here.

entity framwork
                                                                           Image 12.

Now edit any record:

edit any record
                                                                        Image 13.

page at localhost
                                                                     Image 14.

Now delete any record:

delete any record
                                                                     Image 15.