crud operations in gridview using entity framework ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Sunday, 10 September 2017

crud operations in gridview using entity framework

20:34:00 Posted by raviteja swayampu , , No comments
Hi every one again.As a Dot net developer i have been writing articles on real time application on this blog.Many of my readers asked me(through comments and email) to write about asp.net web development also.So, i decided to write asp.net articles along with real time applications also.The current article is step by step procedure to implement basic crud operations on grid view in asp.net with entity framework as data base framework.


Other related articles on crud operations in this blog is as follows,
Now come to current article.In this article we gonna learn about basic crud operations on grid view(create,retrive,update and delete operations) along with cascading drop down list in create and update forms.

crud operations in gridview using entity framework

Topics covered in this article
1.Creating database for crud operations and cascading dropdownlist
2.Binding gridview with database data using entity framework
3.performing create,delete,update and retrive operations on grid.
4.Styling grid with responsive twitter bootstrap.

Steps to implement crud operations on gridview

1.Create asp.net web application with empty webforms template.
2.Create following tables in database to perform crud operations and implementing cascading drop down list functionality in grid.
CREATE TABLE [dbo].[Contacts] (
    [ContactID]     INT           IDENTITY (1, 1) NOT NULL,
    [ContactPerson] VARCHAR (100) NOT NULL,
    [ContactNo]     VARCHAR (20)  NOT NULL,
    [CountryID]     INT           NOT NULL,
    [StateID]       INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([ContactID] ASC)
);

CREATE TABLE [dbo].[Country] (
    [CountryID]   INT           IDENTITY (1, 1) NOT NULL,
    [CountryName] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([CountryID] ASC)
);

CREATE TABLE [dbo].[State] (
    [StateID]   INT           IDENTITY (1, 1) NOT NULL,
    [CountryID] INT           NOT NULL,
    [StateName] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([StateID] ASC)
);

SET IDENTITY_INSERT [dbo].[Country] ON
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (1, N'Brazil')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (2, N'China')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (3, N'France')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (4, N'India')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (5, N'USA')
SET IDENTITY_INSERT [dbo].[Country] OFF

SET IDENTITY_INSERT [dbo].[Contacts] ON
INSERT INTO [dbo].[Contacts] ([ContactID], [ContactPerson], [ContactNo], [CountryID], [StateID]) VALUES (1, N'Ravi teja', N'90545647865', 1, 49)
INSERT INTO [dbo].[Contacts] ([ContactID], [ContactPerson], [ContactNo], [CountryID], [StateID]) VALUES (2, N'Gopal', N'89767856457', 1, 163)
INSERT INTO [dbo].[Contacts] ([ContactID], [ContactPerson], [ContactNo], [CountryID], [StateID]) VALUES (3, N'Sridhar', N'09435898445', 1, 148)
SET IDENTITY_INSERT [dbo].[Contacts] OFF

SET IDENTITY_INSERT [dbo].[State] ON
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (1, 5, N'California')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (2, 2, N'Beijing')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (3, 5, N'Iowa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (4, 5, N'New York')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (5, 2, N'Hebei')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (6, 2, N'Jiangsu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (7, 5, N'New Jersey')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (8, 5, N'Massachusetts')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (9, 5, N'Connecticut')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (10, 2, N'Guangdong')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (11, 5, N'Florida')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (12, 5, N'Texas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (13, 5, N'Armed Forces US')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (14, 5, N'Tennessee')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (15, 5, N'Kentucky')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (16, 3, N'Ile-de-3nce')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (17, 5, N'Georgia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (18, 1, N'Rio de Janeiro')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (19, 5, N'Illinois')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (20, 1, N'Ceara')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (21, 5, N'Colorado')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (22, 2, N'Zhejiang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (23, 5, N'Utah')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (24, 2, N'Liaoning')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (25, 4, N'Haryana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (26, 5, N'Maryland')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (27, 2, N'Shanghai')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (28, 2, N'Tianjin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (29, 5, N'South Carolina')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (30, 5, N'Montana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (31, 5, N'Louisiana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (32, 2, N'Fujian')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (33, 1, N'Santa Catarina')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (34, 1, N'Espirito Santo')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (35, 5, N'Washington')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (36, 4, N'Andhra Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (37, 5, N'Pennsylvania')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (38, 2, N'Guangxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (39, 5, N'North Carolina')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (40, 2, N'Shandong')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (41, 2, N'Chongqing')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (42, 5, N'Michigan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (43, 2, N'Hubei')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (44, 4, N'Delhi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (45, 5, N'Arkansas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (46, 5, N'Wisconsin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (47, 3, N'Midi-Pyrenees')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (48, 3, N'Picardie')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (49, 1, N'Bahia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (50, 2, N'Heilongjiang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (51, 4, N'Tamil Nadu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (52, 5, N'Ohio')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (53, 5, N'New Mexico')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (54, 5, N'Kansas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (55, 5, N'Oregon')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (56, 4, N'Uttar Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (57, 5, N'Ne1ska')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (58, 5, N'West Virginia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (59, 5, N'Virginia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (60, 5, N'Missouri')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (61, 5, N'Mississippi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (62, 5, N'Rhode Island')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (63, 1, N'Sao Paulo')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (64, 2, N'Shanxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (65, 4, N'Karnataka')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (66, 2, N'Hunan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (67, 5, N'4iana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (68, 5, N'Oklahoma')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (69, 5, N'Minnesota')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (70, 5, N'Alabama')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (71, 2, N'Hainan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (72, 5, N'Arizona')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (73, 2, N'Sichuan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (74, 5, N'South Dakota')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (75, 4, N'Maharashtra')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (76, 5, N'Nevada')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (77, 2, N'Henan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (78, 4, N'Kerala')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (79, 5, N'New Hampshire')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (80, 5, N'Maine')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (81, 5, N'Hawaii')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (82, 4, N'Chhattisgarh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (83, 2, N'Anhui')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (84, 5, N'District of Columbia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (85, 5, N'Delaware')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (86, 4, N'West Bengal')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (87, 2, N'Shaanxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (88, 4, N'Madhya Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (89, 4, N'Gujarat')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (90, 3, N'3nche-Comte')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (91, 5, N'Idaho')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (92, 4, N'Rajasthan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (93, 2, N'Nei Mongol')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (94, 3, N'Alsace')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (95, 4, N'Orissa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (96, 2, N'Jilin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (97, 4, N'Jharkhand')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (98, 4, N'Chandigarh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (99, 4, N'Punjab')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (100, 3, N'Languedoc-Roussillon')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (101, 4, N'Assam')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (102, 3, N'Centre')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (103, 3, N'Champagne-Ardenne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (104, 3, N'Bretagne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (105, 3, N'Rhone-Alpes')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (106, 3, N'Nord-Pas-de-Calais')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (107, 3, N'Lorraine')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (108, 1, N'Rio Grande do Sul')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (109, 3, N'Provence-Alpes-Cote d''Azur')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (110, 1, N'Minas Gerais')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (111, 3, N'Limousin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (112, 2, N'Guizhou')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (113, 3, N'Haute-Normandie')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (114, 3, N'Poitou-Charentes')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (115, 5, N'Wyoming')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (116, 4, N'Daman and Diu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (117, 1, N'Para')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (118, 3, N'Basse-Normandie')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (119, 4, N'Bihar')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (120, 3, N'Aquitaine')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (121, 1, N'Parana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (122, 3, N'Auvergne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (123, 1, N'Pernambuco')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (124, 3, N'Pays de la Loire')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (125, 1, N'Amazonas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (126, 1, N'Distrito Federal')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (127, 5, N'North Dakota')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (128, 3, N'Bourgogne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (129, 5, N'Vermont')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (130, 1, N'Goias')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (131, 4, N'Himachal Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (132, 1, N'Sergipe')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (133, 5, N'Alaska')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (134, 1, N'Mato Grosso do Sul')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (135, 2, N'Yunnan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (136, 4, N'Uttarakhand')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (137, 4, N'Meghalaya')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (138, 2, N'Jiangxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (139, 1, N'Rio Grande do Norte')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (140, 1, N'Paraiba')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (141, 1, N'Piaui')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (142, 2, N'Gansu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (143, 4, N'Jammu and Kashmir')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (144, 4, N'Goa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (145, 1, N'Maranhao')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (146, 1, N'Mato Grosso')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (147, 3, N'Corse')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (148, 1, N'Alagoas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (149, 4, N'Puducherry')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (150, 4, N'Manipur')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (151, 1, N'Tocantins')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (152, 1, N'Roraima')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (153, 1, N'Rondonia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (154, 2, N'Xizang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (155, 2, N'Ningxia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (156, 2, N'Xinjiang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (157, 2, N'Qinghai')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (158, 4, N'Mizoram')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (159, 4, N'Dadra and Nagar Haveli')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (160, 4, N'Arunachal Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (161, 4, N'Tripura')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (162, 1, N'Amapa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (163, 1, N'Acre')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (164, 4, N'Sikkim')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (165, 4, N'Nagaland')
SET IDENTITY_INSERT [dbo].[State] OFF

3.Right click on Models folder --> Add --> ADO.NET Entity DataModel --> Name it --> Select EF designer from Database from Entity Data Model Wizard --> Select connection string and web.config --> click next --> Choose your database objects and settings(here table you created) and give name to model namespace--> click finish.
4.Add webform to solution by right click --> Add --> webform -->name it.
5.Now replace the aspx page code with below code.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridView.aspx.cs" Inherits="CRUDUsingEF.Contacts" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>www.mitechdev.com</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <style type="text/css">
        input{max-width:150px;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h3 class="text-info">Grid view Using EF</h3>
        <asp:GridView ID="gridview" runat="server" AutoGenerateColumns="false"
            DataKeyNames="ContactID,CountryID,StateID" CellPadding="10" CellSpacing="0"
            ShowFooter="true"
            CssClass="table table-responsive table-striped" OnRowCommand="gridview_RowCommand" OnRowCancelingEdit="gridview_RowCancelingEdit" OnRowDeleting="gridview_RowDeleting" OnRowEditing="gridview_RowEditing" OnRowUpdating="gridview_RowUpdating">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>Contact Person</HeaderTemplate>
                    <ItemTemplate><%#Eval("ContactPerson") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox cssClass="form-control" 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 cssClass="form-control" 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 cssClass="form-control" 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 cssClass="form-control" 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 cssClass="form-control" 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 cssClass="form-control" 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 cssClass="form-control" 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 cssClass="form-control" 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" cssClass="btn btn-success" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                        &nbsp;|&nbsp;
                        <asp:LinkButton ID="lbDelete" cssClass="btn btn-danger" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you confirm?')">Delete</asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lbUpdate" cssClass="btn btn-success" runat="server" CommandName="Update" ValidationGroup="edit">Update</asp:LinkButton>
                        &nbsp;|&nbsp;
                        <asp:LinkButton ID="lbCancel" cssClass="btn btn-default" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="btnInsert" cssClass="btn btn-success" runat="server" Text="Save" CommandName="Insert" ValidationGroup="Add" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
6.Here, I took the grid templates to perform the operations.The design of grid look like below.

crud operations in gridview using entity framework

7.Now switch to gridview.aspx.cs file and add below methods,
1.To fetch and bind database data to gridview.
2.To implement cascading drop down list of country and state.
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //binds all contacts to grid
                LoadContacts();
            }
        }
        //fetch data from database and binds it to grid
        private void LoadContacts()
        {
            List 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();
                    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)
                {
                    allContacts.Add(new Contact());
                    gridview.DataSource = allContacts;
                    gridview.DataBind();
                    gridview.Rows[0].Visible = false;
                }
                else
                {
                    gridview.DataSource = allContacts;
                    gridview.DataBind();
                }
                if (gridview.Rows.Count > 0)
                {
                    DropDownList dd = (DropDownList)gridview.FooterRow.FindControl("ddCountry");
                    BindCountry(dd, PopulateCountry());
                }
            }
        }
        //fetches country dropdown data from database
        private List PopulateCountry()
        {
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                return dc.Countries.OrderBy(a => a.CountryName).ToList();
            }
        }
        ////fetches states dropdownlist data from db
        private List PopulateState(int countryID)
        {
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
            }
        }
        //binds countries list data to country dropdownlist
        private void BindCountry(DropDownList ddCountry, List 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();
        }
        //binds state dropdownlist data to state 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();
        }
        //this method fires when country dropdown list selection changes.
        //and binds respective state to state dropdownlist.
        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));
        }


8.Now to perform CRUD operations on grid view create and implement below methods.
//inserts record into grid
        protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                Page.Validate("Add");
                if (Page.IsValid)
                {
                    var fRow = gridview.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())
                    {
                        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();
                        LoadContacts();
                    }
                }
            }
        }
        //fetches the record from db based on record id
        protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string countryID = gridview.DataKeys[e.NewEditIndex]["CountryID"].ToString();
            string stateID = gridview.DataKeys[e.NewEditIndex]["StateID"].ToString();
            gridview.EditIndex = e.NewEditIndex;
            LoadContacts();
            DropDownList ddCountry = (DropDownList)gridview.Rows[e.NewEditIndex].FindControl("ddCountry");
            DropDownList ddState = (DropDownList)gridview.Rows[e.NewEditIndex].FindControl("ddState");
            if (ddCountry != null && ddState != null)
            {
                BindCountry(ddCountry, PopulateCountry());
                ddCountry.SelectedValue = countryID;
                BindState(ddState, Convert.ToInt32(countryID));
                ddState.SelectedValue = stateID;
            }
        }
        //cancels the updation of record
        protected void gridview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //Cancel Edit Mode 
            gridview.EditIndex = -1;
            LoadContacts();
        }
        //updates the record on db
        protected void gridview_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("edit");
            if (!Page.IsValid)
            {
                return;
            }
            int contactID = (int)gridview.DataKeys[e.RowIndex]["ContactID"];
            TextBox txtContactPerson = (TextBox)gridview.Rows[e.RowIndex].FindControl("txtContactPerson");
            TextBox txtContactNo = (TextBox)gridview.Rows[e.RowIndex].FindControl("txtContactNo");
            DropDownList ddCountry = (DropDownList)gridview.Rows[e.RowIndex].FindControl("ddCountry");
            DropDownList ddState = (DropDownList)gridview.Rows[e.RowIndex].FindControl("ddState");
            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();
                gridview.EditIndex = -1;
                LoadContacts();
            }
        }
        //delete the selected record from grid
        protected void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int contactID = (int)gridview.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();
                    LoadContacts();
                }
            }
        }

delete operation in gridview

9.For styling this grid i used twitter bootstrap css framework classes in grid.
10.Download source code this application from Github.

Conclusion:

I hope this article will help you .To get more updates please subscribe to this blog subscribe.

0 comments:

Post a Comment