Sunday, September 6, 2015

Asp.net Select, Edit, Update and Delete record in Gridview using Entity Framework

In this article I am going to explain how to Edit, update and delete the record in Gridview data control using Entity Framework and Asp.net

Description:

I have created a table Movie in database and inserted the records into it. Now I will fetch the records from this table and display them in Gridview data control and edit, update and delete the record.

Implementation:
To set up the ADO.net entity framework project read the article How to setupADO.net Entity Framework project or website in asp.net.

Add a webform to project/website.

HTML Markup of webform (Gridview):
      <fieldset style="width:600px;">
            <legend>Entity Framework Tutorial</legend>
     <asp:GridView ID="grdmovie" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="Id"
     CellPadding="4" ForeColor="#333333" GridLines="None">
  <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtname" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Genre">
            <ItemTemplate>
               <asp:Label ID="lblgenre" runat="server" Text='<%# Eval("Genre") %>'></asp:Label>
            </ItemTemplate>
             <EditItemTemplate>
                <asp:TextBox ID="txtgenre" runat="server" Text='<%# Eval("Genre") %>'></asp:TextBox>
            </EditItemTemplate>
             <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Budget(In Crore)">
            <ItemTemplate>
               <asp:Label ID="lblcost" runat="server" Text='<%# Eval("Cost") %>'></asp:Label>
            </ItemTemplate>
             <EditItemTemplate>
                <asp:TextBox ID="txtcost" runat="server" Text='<%# Eval("Cost") %>'></asp:TextBox>
            </EditItemTemplate>
             <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
           <asp:TemplateField HeaderText="Poster">
            <ItemTemplate>
                 <asp:Image ID="Image1" ImageUrl='<%# Eval("Poster") %>' runat="server" width="200px"/>
            </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
        </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
             <asp:ImageButton ID="imgbtnedit" runat="server" ImageUrl="~/btnimages/edit.png" CommandName="Edit" CausesValidation="false"/> <asp:ImageButton ID="imgbtndelete" runat="server" ImageUrl="~/btnimages/delete.png" CommandName="Delete" CausesValidation="false"/>
            </ItemTemplate>
                <EditItemTemplate>
                    <asp:ImageButton ID="imgcancel" runat="server" ImageUrl="~/btnimages/cancel.png" CommandName="Cancel" CausesValidation="false"/><asp:ImageButton ID="imgupdate" runat="server" ImageUrl="~/btnimages/update.png" CommandName="Update" CausesValidation="false"/>
                     </EditItemTemplate>
                <ItemStyle VerticalAlign="Top" Width="400px" />
        </asp:TemplateField>
    </Columns>
                       <EditRowStyle BackColor="#999999" />
                       <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                       <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                       <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                       <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                       <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                       <SortedAscendingCellStyle BackColor="#E9E7E2" />
                       <SortedAscendingHeaderStyle BackColor="#506C8C" />
                       <SortedDescendingCellStyle BackColor="#FFFDF8" />
                       <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>                 
        </fieldset>

Create the object of entity web.config:
C#:
DemoEntities db = new DemoEntities();

VB:
Dim db As New DemoEntities

Write the function to bind the Gridview and call it on page load event.
C#:
protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindGrid();
        }
    }
public void BindGrid()
    {
        try
        {
            var bindgrid = db.Movies.Select(m => m);
            grdmovie.DataSource = bindgrid.ToList();
            grdmovie.DataBind();
        }
        catch(Exception ex)
        { }
    }

VB:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGrid()
        End If
    End Sub
    Public Sub BindGrid()
        Dim bindgrid = db.Movies.[Select](Function(m) m)
        grdmovie.DataSource = bindgrid.ToList()
        grdmovie.DataBind()
    End Sub

Edit the record
Write the below given code on reediting event of Gridview control.
C#:
protected void grdmovie_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdmovie.EditIndex = e.NewEditIndex;
        BindGrid();
    }

VB:
Protected Sub grdmovie_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles grdmovie.RowEditing
        grdmovie.EditIndex = e.NewEditIndex
        BindGrid()
    End Sub

Update the record
Write the below given code on RowUpdateing event of Gridview control.
C#:
protected void grdmovie_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            int id = Convert.ToInt32(grdmovie.DataKeys[e.RowIndex].Value);
            TextBox txtname = (TextBox)grdmovie.Rows[e.RowIndex].FindControl("txtname");
            TextBox txtgenre = (TextBox)grdmovie.Rows[e.RowIndex].FindControl("txtgenre");
            TextBox txtcost = (TextBox)grdmovie.Rows[e.RowIndex].FindControl("txtcost");
            Movie objtb = (from m in db.Movies
                           where m.Id == id
                           select m).FirstOrDefault();
            objtb.Name = txtname.Text;
            objtb.Genre = txtgenre.Text;
            objtb.Cost = Convert.ToInt32(txtcost.Text);
            db.SaveChanges();
            grdmovie.EditIndex = -1;
            BindGrid();
            Response.Write("<script>alert('Record Updated Successfully');</script>");
        }
        catch(Exception ex)
        { }
    }

VB:
Protected Sub grdmovie_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles grdmovie.RowUpdating
        Try
            Dim id As Integer = Convert.ToInt32(grdmovie.DataKeys(e.RowIndex).Value)
            Dim txtname As TextBox = DirectCast(grdmovie.Rows(e.RowIndex).FindControl("txtname"), TextBox)
            Dim txtgenre As TextBox = DirectCast(grdmovie.Rows(e.RowIndex).FindControl("txtgenre"), TextBox)
            Dim txtcost As TextBox = DirectCast(grdmovie.Rows(e.RowIndex).FindControl("txtcost"), TextBox)
            Dim objtb As Movie = (From m In db.Movies Where m.Id = id).FirstOrDefault()
            objtb.Name = txtname.Text
            objtb.Genre = txtgenre.Text
            objtb.Cost = Convert.ToInt32(txtcost.Text)
            db.SaveChanges()
            grdmovie.EditIndex = -1
            BindGrid()
            Response.Write("<script>alert('Record Updated Successfully');</script>")
        Catch ex As Exception
        End Try
    End Sub

Cancel the edit mode of Gridview
C#:
protected void grdmovie_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdmovie.EditIndex = -1;
        BindGrid();
    }

VB:
Protected Sub grdmovie_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles grdmovie.RowCancelingEdit
        grdmovie.EditIndex = -1
        BindGrid()
    End Sub

Delete the record
On RowDeleting event of Gridview write the below given code.
C#:
protected void grdmovie_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int id = Convert.ToInt32(grdmovie.DataKeys[e.RowIndex].Value);
            Movie objtb = db.Movies.First(x => x.Id == id);
            db.Movies.Remove(objtb);
            db.SaveChanges();
            BindGrid();
            Response.Write("<script>alert('Record Deleted Successfully');</script>");
        }
        catch (Exception ex)
        { }
    }

VB:
  Protected Sub grdmovie_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grdmovie.RowDeleting
        Try
            Dim id As Integer = Convert.ToInt32(grdmovie.DataKeys(e.RowIndex).Value)
            Dim objtb As Movie = db.Movies.First(Function(x) x.Id = id)
            db.Movies.Remove(objtb)
            db.SaveChanges()
            BindGrid()
            Response.Write("<script>alert('Record Deleted Successfully');</script>")
        Catch ex As Exception
        End Try
    End Sub

Build and run the project/website. Now test it. Hope it helps you.
Demo:
Asp.net Select, Edit, Update and Delete record in Gridview using Entity Framework

  In this article we have learn to how to Select, Edit, Update and Delete the record using Entity Framework 6.0 in asp.net Visual studio 2013I hope you enjoyed this article. 

1 comment:

  1. Google Search needs to put this on the top of the list. Got me up and running in one night!

    ReplyDelete