-->

How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET Webforms application


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.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net ASP.NET Webforms application > Entry Application Name > Click OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create tables for perform CRUD Operation.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used 3 tables as below

Contacts

Countries

States


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Folder

Here I have created a folder Named "ExtendedModel" in which we will create a class
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New Folder > Rename Folder.

Step-6: Create a (partial) Class for extend 2 fileds CountryName and StateName

Here I have created a (partial) class named "Contact"
Go to Solution Explorer > Right Click on the Folder > Add > Class > Enter class name > Add.

[N:B: I have changed namespace of the class "ASPCRUDPart1.ExtendedModel" to "ASPCRUDPart1" and make it partial class]
 
namespace ASPCRUDPart1
{
    public partial class Contact
    {
        public string CountryName { get; set; }
        public string StateName { get; set; }
    }
}
    

Step-7: Add a Webpage and Design for implementing CRUD operation in asp.net gridview.

(Optional)Here I have deleted Contact.aspx page (default generated page) as there is a class (model) named "Contact". If there is also in your application please rename the page or the model
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Contacts.aspx.cs" Inherits="ASPCRUDPart1.Contacts" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        /*Here I will add some css for looks good*/
        .myGrid {
            border: 1px solid #ddd;
            margin: 15px;
            -webkit-border-radius: 3px 3px 0 0;
            -moz-border-radius: 3px 3px 0 0;
            border-radius: 3px 3px 0 0;
        }
        .myGrid td {
            vertical-align:top;
        }
        .header {
            overflow: hidden;
            position: relative;
            border-bottom: 1px solid #ddd;
            height: 30px;
        }

            .header th {
                color: #222;
                font-weight: normal;
                line-height: 40px;
                text-align: left;
                /* text-shadow: 0 1px #FFFFFF; */
                white-space: nowrap;
                border-right: 1px solid #ddd;
                border-bottom: 2px solid #ddd;
                padding: 0px 15px 0px 15px;
                -webkit-border-radius: 1px;
                -moz-border-radius: 1px;
            }

        .trow1 {
            background: #f9f9f9;
        }

        .trow2 {
            background: #fff;
        }

            .trow1 td, .trow2 td {
                color: #555;
                line-height: 18px;
                padding: 9px 5px;
                text-align: left;
                border-right: 1px solid #ddd;
                border-bottom: 1px solid #ddd;
                text-align: left;
                
            }

        input[type='text'],select {
            border: 1px solid #b8b8b8;
            border-radius: 3px;
            color: #999999;
            float: left;
            height: 22px;
            padding: 0 5px;
            position: relative;
            width: 185px;            
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <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">

            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>Contact Person</HeaderTemplate>
                    <ItemTemplate><%#Eval("ContactPerson") %></ItemTemplate>
                    <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>
                    <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>
                    <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>
                    <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>
                        &nbsp;|&nbsp;
                        <asp:LinkButton ID="lbDelete" runat="server" CommandName="Delete">Delete</asp:LinkButton>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="btnInsert" runat="server" Text="Save" CommandName="Insert" ValidationGroup="Add" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>

        </asp:GridView>
    </div>
    </form>
</body>
</html>

    

Step-8: Write function for fetch country from database.

 
private List<Country> PopulateCountry()
{
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        return dc.Countries.OrderBy(a => a.CountryName).ToList();
    }
}
    

Step-9: Write function for fetch state from database.

 
private List<State> PopulateState(int countryID)
{
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
    }
}
    

Step-10: Write function for bind countries with dropdown.

 
private void BindCountry(DropDownList ddCountry, List<Country> country)
{
    ddCountry.Items.Clear();
    ddCountry.Items.Add(new ListItem { Text = "Select Country", Value = "0" });
    ddCountry.AppendDataBoundItems = true;

    ddCountry.DataTextField = "CountryName";
    ddCountry.DataValueField = "CountryID";
    ddCountry.DataSource = country;
    ddCountry.DataBind();
}
    

Step-11: Write function for bind states with dropdown.

 
private void BindState(DropDownList ddState, int countryID)
{
    ddState.Items.Clear();
    ddState.Items.Add(new ListItem { Text = "Select State", Value = "0" });
    ddState.AppendDataBoundItems = true;

    ddState.DataTextField = "StateName";
    ddState.DataValueField = "StateID";
    ddState.DataSource = countryID > 0 ? PopulateState(countryID) : null;
    ddState.DataBind();
}
    

Step-12: Write function for fetch data from database and show in the gridview (Read Operation of CRUD).


 
private void PopulateContacts()
{
    List<Contact> allContacts = null;
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var contacts = (from a in dc.Contacts
                        join b in dc.Countries on a.CountryID equals b.CountryID
                        join c in dc.States on a.StateID equals c.StateID
                        select new
                        {
                            a,
                            b.CountryName,
                            c.StateName
                        });
        if (contacts != null)
        {
            allContacts = new List<Contact>();
            foreach (var i in contacts)
            {
                Contact c = i.a;
                c.CountryName = i.CountryName;
                c.StateName = i.StateName;
                allContacts.Add(c);
            }
        }

        if (allContacts==null || allContacts.Count == 0)
        {
            //trick to show footer when there is no data in the gridview
            allContacts.Add(new Contact());
            myGridview.DataSource = allContacts;
            myGridview.DataBind();
            myGridview.Rows[0].Visible = false;
        }
        else
        {
            myGridview.DataSource = allContacts;
            myGridview.DataBind();
        }

        //Populate & bind country
        if (myGridview.Rows.Count > 0)
        {
            DropDownList dd = (DropDownList)myGridview.FooterRow.FindControl("ddCountry");
            BindCountry(dd, PopulateCountry());
        }

    }
}
    

Step-13: Add below code to the page load event for show Database data in the gridview.


 
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PopulateContacts();
    }
}
    

Step-14: Add below code to the country dropdown SelectedIndexChanged event for load state.


 
protected void ddCountry_SelectedIndexChanged(object sender, EventArgs e)
{
    //write code for cascade dropdown
    string countryID = ((DropDownList)sender).SelectedValue;
    var dd = (DropDownList)((System.Web.UI.WebControls.ListControl)(sender)).Parent.Parent.FindControl("ddState");
    BindState(dd, Convert.ToInt32(countryID));
}
    

Step-15: Add below code to the gridview RowCommand event for Save new data.


 
protected void myGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //Insert new contact
    if (e.CommandName == "Insert")
    {
        Page.Validate("Add");
        if (Page.IsValid)
        {
            var fRow = myGridview.FooterRow;
            TextBox txtContactPerson = (TextBox)fRow.FindControl("txtContactPerson");
            TextBox txtContactNo = (TextBox)fRow.FindControl("txtContactNo");
            DropDownList ddCountry = (DropDownList)fRow.FindControl("ddCountry");
            DropDownList ddState = (DropDownList)fRow.FindControl("ddState");
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {

                //Here in this example we have done a little mistake // class name and page name is Same (contact) 
                // We will remove contact page , as its not in use

                dc.Contacts.Add(new Contact
                {
                        ContactPerson = txtContactPerson.Text.Trim(),
                        ContactNo = txtContactNo.Text.Trim(),
                        CountryID = Convert.ToInt32(ddCountry.SelectedValue),
                            StateID = Convert.ToInt32(ddState.SelectedValue)
                });
                dc.SaveChanges();
                PopulateContacts();
            }
        }
    }
}
    

Step-16: Run Application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.