Introduction
In this post, How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET Webforms application.CRUD is an abbreviation for Create, Read, Update and Delete. The GridView control in ASP.NET Webforms is a great tool to use to perform CRUD operations. It provides for a very efficient and user friendly interface with which to manipulate data. In this article I am going to explain how we can use asp.net Gridview control to perform CRUD operations with all the necessary functionalities like validation, cascade dropdown inside gridview etc.
I have split the entire application split into following 2 parts for making things more simple and understandable specially for beginners.
- Part 1 : Perform read and create functionality of CRUD Operation.
- Part 2 : Perform update and delete functionality of CRUD Operation.
Steps :
Step - 1 : Insert EditItemTemplate into our gridview for Make it editable
Open our page in design view (here Contacts.aspx) and insert edit item templete for make the grid editableComplete HTML of Gridview
<asp:GridView ID="myGridview" runat="server" AutoGenerateColumns="false" DataKeyNames="ContactID,CountryID,StateID" CellPadding="10" CellSpacing="0" ShowFooter="true" CssClass="myGrid" HeaderStyle-CssClass="header" RowStyle-CssClass="trow1" AlternatingRowStyle-CssClass="trow2" OnRowCommand="myGridview_RowCommand" OnRowCancelingEdit="myGridview_RowCancelingEdit" OnRowDeleting="myGridview_RowDeleting" OnRowEditing="myGridview_RowEditing" OnRowUpdating="myGridview_RowUpdating"> <Columns> <asp:TemplateField> <HeaderTemplate>Contact Person</HeaderTemplate> <ItemTemplate><%#Eval("ContactPerson") %></ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtContactPerson" runat="server" Text='<%#Bind("ContactPerson") %>' /> <asp:RequiredFieldValidator ID="rfCPEdit" runat="server" ForeColor="Red" ErrorMessage="*" Display="Dynamic" ValidationGroup="edit" ControlToValidate="txtContactPerson">Required</asp:RequiredFieldValidator> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtContactPerson" runat="server"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="rfCP" runat="server" ErrorMessage="*" ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtContactPerson">Required</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate>Contact No</HeaderTemplate> <ItemTemplate><%#Eval("ContactNo") %></ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtContactNo" runat="server" Text='<%#Bind("ContactNo") %>' /> <asp:RequiredFieldValidator ID="rfCNEdit" runat="server" ErrorMessage="*" Display="Dynamic" ForeColor="Red" ValidationGroup="edit" ControlToValidate="txtContactNo">Required</asp:RequiredFieldValidator> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtContactNo" runat="server"></asp:TextBox><br /> <asp:RequiredFieldValidator ID="rfCN" runat="server" ErrorMessage="*" ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtContactNo">Required</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate>Country</HeaderTemplate> <ItemTemplate><%#Eval("CountryName") %></ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddCountry_SelectedIndexChanged"> <asp:ListItem Text="Select Country" Value="0"></asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ID="rfCEdit" runat="server" ErrorMessage="*" ForeColor="Red" Display="Dynamic" ValidationGroup="edit" ControlToValidate="ddCountry" InitialValue="0"> Required </asp:RequiredFieldValidator> </EditItemTemplate> <FooterTemplate> <asp:DropDownList ID="ddCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddCountry_SelectedIndexChanged"> <asp:ListItem Text="Select Country" Value="0"></asp:ListItem> </asp:DropDownList> <br /> <asp:RequiredFieldValidator ID="rfC" runat="server" ErrorMessage="*" ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="ddCountry" InitialValue="0">Required</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate>State</HeaderTemplate> <ItemTemplate><%#Eval("StateName") %></ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddState" runat="server"> <asp:ListItem Text="Select State" Value="0"></asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ID="rfSEdit" runat="server" ErrorMessage="*" ForeColor="Red" Display="Dynamic" ValidationGroup="edit" ControlToValidate="ddState" InitialValue="0"> Required </asp:RequiredFieldValidator> </EditItemTemplate> <FooterTemplate> <asp:DropDownList ID="ddState" runat="server"> <asp:ListItem Text="Select State" Value="0"></asp:ListItem> </asp:DropDownList><br /> <asp:RequiredFieldValidator ID="rfS" runat="server" ErrorMessage="*" ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="ddState" InitialValue="0">Required</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lbEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton> | <asp:LinkButton ID="lbDelete" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you confirm?')">Delete</asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lbUpdate" runat="server" CommandName="Update" ValidationGroup="edit">Update</asp:LinkButton> | <asp:LinkButton ID="lbCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton> </EditItemTemplate> <FooterTemplate> <asp:Button ID="btnInsert" runat="server" Text="Save" CommandName="Insert" ValidationGroup="Add" /> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Step-2: Add Event OnRowEditing (myGridview_RowEditing) in gridview and write below code for edit mode.
Select Gridview and go to properties > double click on OnRowEditingWrite below code
protected void myGridview_RowEditing(object sender, GridViewEditEventArgs e) { //Get Country ID and State ID of editable row string countryID = myGridview.DataKeys[e.NewEditIndex]["CountryID"].ToString(); string stateID = myGridview.DataKeys[e.NewEditIndex]["StateID"].ToString(); //Open Edit Mode myGridview.EditIndex = e.NewEditIndex; PopulateContacts(); //Populate Country And State and Bind DropDownList ddCountry = (DropDownList)myGridview.Rows[e.NewEditIndex].FindControl("ddCountry"); DropDownList ddState = (DropDownList)myGridview.Rows[e.NewEditIndex].FindControl("ddState"); if (ddCountry != null && ddState != null) { BindCountry(ddCountry, PopulateCountry()); ddCountry.SelectedValue = countryID; BindState(ddState, Convert.ToInt32(countryID)); ddState.SelectedValue = stateID; } }
Step-3: Add Event OnRowCancelingEdit (myGridview_RowCancelingEdit) in gridview and write below code for cancel edit mode.
Select Gridview and go to properties > double click on OnRowCancelingEditWrite below code
protected void myGridview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //Cancel Edit Mode myGridview.EditIndex = -1; PopulateContacts(); }
Step-4: Add Event OnRowUpdating (myGridview_RowUpdating) in gridview and write below code for update
Select Gridview and go to properties > double click on OnRowUpdatingWrite below code
protected void myGridview_RowUpdating(object sender, GridViewUpdateEventArgs e) { //Validate Page Page.Validate("edit"); if (!Page.IsValid) { return; } //Get Contact ID int contactID = (int)myGridview.DataKeys[e.RowIndex]["ContactID"]; //Find Controls TextBox txtContactPerson = (TextBox)myGridview.Rows[e.RowIndex].FindControl("txtContactPerson"); TextBox txtContactNo = (TextBox)myGridview.Rows[e.RowIndex].FindControl("txtContactNo"); DropDownList ddCountry = (DropDownList)myGridview.Rows[e.RowIndex].FindControl("ddCountry"); DropDownList ddState = (DropDownList)myGridview.Rows[e.RowIndex].FindControl("ddState"); //Get Values (updated) and Save to database using (MyDatabaseEntities dc = new MyDatabaseEntities()) { var v = dc.Contacts.Where(a => a.ContactID.Equals(contactID)).FirstOrDefault(); if (v != null) { v.ContactPerson = txtContactPerson.Text.Trim(); v.ContactNo = txtContactNo.Text.Trim(); v.CountryID = Convert.ToInt32(ddCountry.SelectedValue); v.StateID = Convert.ToInt32(ddState.SelectedValue); } dc.SaveChanges(); myGridview.EditIndex = -1; PopulateContacts(); } }
Step-5: Add Event OnRowDeleting (myGridview_RowDeleting) in gridview and write below code for delete
Select Gridview and go to properties > double click on OnRowDeletingWrite below code
protected void myGridview_RowDeleting(object sender, GridViewDeleteEventArgs e) { int contactID = (int)myGridview.DataKeys[e.RowIndex]["ContactID"]; using (MyDatabaseEntities dc = new MyDatabaseEntities()) { var v = dc.Contacts.Where(a => a.ContactID.Equals(contactID)).FirstOrDefault(); if (v != null) { dc.Contacts.Remove(v); dc.SaveChanges(); PopulateContacts(); } } }