This blog will explain you what 3-Tier architecture is and how to create a website using 3-Tier architecture in asp.net using c#. In this blog I have also used Stored Procedure to Insert, Update, Delete and Select data from Database.

What is 3-Tier Architecture?

3-Tier architecture means dividing our project into three different layers which are Presentation Layer, Business Logic Layer and Database Layer. Simply a Layer is portion of code that usually used to perform specific task, so in 3-Tier architecture each layer has its specific task which is explained below.

Presentation Layer

Presentation layer is a User Interface with which user can directly interact. It contains .aspx pages where you can design your user interface with html controls, CSS and JavaScript on it. This layer communicates with Business Logic Layer only.

Business Logic Layer

Business Logic Layer is a middle layer and act as a bridge between Presentation Layer and Database Layer. In this layer you can perform logic according to business requirements such as Validation, Calculation, Click events etc… Basically this layer passes data from presentation layer to database layer.

Database Layer

Database Layer is used to connect our project with SQL database. This layer contains methods, stored procedures which used to perform database related operations such as Insert, Update, Delete and Select. This layer usually communicates with Business Logic Layer. Business layer will call methods of this layer to connect with database.

Execution flow: The execution of 3-Tier starts from presentation layer. When user interact with website and perform some action like click events, data will be pass from Presentation Layer to Business Logic Layer. Business layer process the data like validation and pass it to database layer. Database Layer performs its database task such as Insert, Update, Delete and so on and return back to Business layer. After it, execution return back from business layer to presentation layer and shows messages according to action performed at database layer.

Let understand this coding concept with example. We will use Stored Procedure to perform SQL queries. Before going ahead you can see my old blog CRUD Operation in GridView using ASP.NET to understand basics of creating website and SQL.

Create Presentation Layer

Step 1. Create an empty website from Visual Studio. (Open Visual Studio then select File-> New Web Site OR File-> New-> Web Site)

Step 2. Select Visual C# from left panel and select ASP.NET Empty Web Site from center panel.

Step 3. Now click on Browse button to save your website to proper location.

Step 4. Select proper location (Folder) where you want to save your website and provide a website name after folder name, like “\Desktop\ThreeTierArchitecture” and click OK.

An empty web site has been created.

Step 5. Right click on your website and select Add New Item to add Web Form.

Step 6. Now design form to insert data. Take fields according to our database. As ID is auto increment, do not take it in insert form.

See below code to design form.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Insert</title>

    <style type="text/css">

        table tr td {

            border: 1px solid #CACFD2;

        }

        table {

            margin: 0 auto;

        }

        .clsmargin {

            margin: 0 auto 15px;

            display: table;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server" class="mar-top-10">

        <div style="margin-top: 10%">

            <h2 class="clsmargin">Insert Form</h2>

            <table>

                <tr>

                    <td>Full Name

                    </td>

                    <td>

                        <asp:TextBox ID="txtFullName" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Email Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Password

                    </td>

                    <td>

                        <asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Gender

                    </td>

                    <td>

                        <asp:RadioButton ID="rdoMale" Text="Male" GroupName="Gender" runat="server" />

                        <asp:RadioButton ID="rdoFemale" Text="Female" GroupName="Gender" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Hobbies

                    </td>

                    <td>

                        <asp:CheckBox ID="chkCricket" Text="Cricket" runat="server" />

                        <asp:CheckBox ID="chkFootball" Text="Football" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Profile Picture

                    </td>

                    <td>

                        <asp:FileUpload ID="fileProfilePic" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Button Text="Insert" ID="btnInsert" runat="server" OnClick="btnInsert_Click"/>

                    </td>

                </tr>

            </table>

            <h4 class="clsmargin">

                <asp:Label Text="" ID="lblMsg" runat="server" Style="color: green" />

            </h4>

        </div>

    </form>

</body>

</html>

After completing design, run page to browser. Right click to Default.aspx page in Solution Explorer and select View in Browser. Your page will look like.

As you complete with design, now it’s time to create Database Layer.

Create Database Layer

Before creating Database Layer, you must have to create database, tables and stored procedures.

Create Database, Table and Stored Procedure

Here I have user MSSQL Server Management Studio to create database.

Open SQL Server Management Studio, Connect it and create Database by right clicking on Databases -> Provide a proper name to database e.g. dbThreeTierArchitecture. You can see database is created in Databases tab. Expand Databases tab.

Step 1. Now expand your database and create a table by right clicking on Tables -> New Table. Create a table with your required columns. I have created below table. Please provide at least one column with Primary Key and Auto Increment to identify each and every record unique.

Auto Increment can be given using Identity Specification property of column. Go to the property by right clicking on ID column, Expand Identity Specification property and set IsIdentity to Yes. This property will auto increment ID by 1 and start it from 1. Note that Identity Specification will apply only to int column. To see table please refresh your database.

Step 2. Create Stored Procedures for Insert, Update, Delete and Select operations.

Expand Programmability and right click on Stored Procedures to create stored procedure.

Delete all the statements and write following code to create Stored Procedures. Remember one thing you have to execute procedure after creating it. Execute option is given in toolbar or you can use F5. Refresh Programmability tab to see your created stored procedures.

Stored Procedure to insert records

CREATE PROCEDURE spInsert

(

@FullName VARCHAR(50)

,@EmailAddress VARCHAR(50)

,@Password VARCHAR(150)

,@Gender VARCHAR(8)

,@Hobbies VARCHAR(50)

,@ProfilePic VARCHAR(50)

)

AS

BEGIN

    INSERT INTO tblRegistration

   (

    FullName

           ,EmailAddress

           ,Password

           ,Gender

           ,Hobbies

           ,ProfilePic

   )

VALUES

   (

    @FullName

           ,@EmailAddress

           ,@Password

           ,@Gender

           ,@Hobbies

           ,@ProfilePic

   )

END

Stored Procedure to select records

CREATE PROCEDURE spSelect

AS

BEGIN

    SELECT * FROM tblRegistration

END

Stored Procedure to select records by ID

CREATE PROCEDURE spSelectUserById

(

@ID INT

)

AS

BEGIN

    SELECT * FROM tblRegistration WHERE ID = @ID

END

Stored Procedure to update records

CREATE PROCEDURE spUpdate

(

@ID INT

,@FullName VARCHAR(50)

,@EmailAddress VARCHAR(50)

,@Password VARCHAR(150)

,@Gender VARCHAR(8)

,@Hobbies VARCHAR(50)

,@ProfilePic VARCHAR(50)

)

AS

BEGIN

    UPDATE tblRegistration

SET FullName = @FullName

           ,EmailAddress = @EmailAddress

           ,Password = @Password

           ,Gender = @Gender

           ,Hobbies = @Hobbies

           ,ProfilePic = @ProfilePic

WHERE ID = @ID

END

Stored Procedure to delete records

CREATE PROCEDURE spDelete

(

@ID INT

)

AS

BEGIN

    DELETE FROM tblRegistration WHERE ID = @ID

END

Note: You can modify the stored procedures. Refresh Programmability tab to see your created stored procedures. Right click on your procedure -> Modify. After modifying it again you must have to execute procedure to save your changes.

Create a Class File – Database Layer

Step 1. To add database layer to your web site Right click on your website -> select Add New Item -> select Class -> change name to DatabaseLayer.cs -> click on Add button. .cs file will be added to your project. Database Layer contains Property and Methods for performing database operations.

Step 2. To pass values from Business Logic Layer to Database Layer, we have to create {get; set;} properties.

What is Property?

Property is nothing but a public way of getting and setting values, while hiding implementation code. It will help class to expose itself without being enabled to outside. Property is a class member which provides a mechanism to read and write value from outside class. Basically here both business layer and database layer are separate class that’s why property will help us to pass value from Business Layer to Database Layer.

Example:

public string FullName { get; set; }

Create all properties according to database columns.

Step 3. Create methods to perform Insert, Update, Delete and Select operations in Database Layer. Please see below code to create properties and methods.

DatabaseLayer.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.SqlClient; /* Add this Namespace */

using System.Data; /* Add this Namespace */

  

public class DatabaseLayer

{

    public DatabaseLayer()

    {

    }

    /* Connection String */

    private string strCon = @"Data Source=DELL-PC;Initial Catalog=dbThreeTierArchitecture;Integrated Security=True";

  

    /* { get; set; } Properties */

    public int ID { get; set; }

    public string FullName { get; set; }

    public string EmailAddress { get; set; }

    public string Password { get; set; }

    public string Gender { get; set; }

    public string Hobbies { get; set; }

    public string ProfilePic { get; set; }

  

    /* Methods */

    public int fnInsert(DatabaseLayer objDL)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "spInsert";  /* Stored Procedure name */

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Connection = con;

  

        /* Getting value from property and passing it to parameters declared in Stored Procedure. */

        cmd.Parameters.AddWithValue("@FullName", objDL.FullName); /* Write parameter name same declared in stored procedure i.e @FullName */

        cmd.Parameters.AddWithValue("@EmailAddress", objDL.EmailAddress);

        cmd.Parameters.AddWithValue("@Password", objDL.Password);

        cmd.Parameters.AddWithValue("@Gender", objDL.Gender);

        cmd.Parameters.AddWithValue("@Hobbies", objDL.Hobbies);

        cmd.Parameters.AddWithValue("@ProfilePic", objDL.ProfilePic);

  

        con.Open();

        int isInserted = cmd.ExecuteNonQuery();

        con.Close();

  

        return isInserted;

    }

  

    public DataTable fnSelect()

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "spSelect";

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Connection = con;

  

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();

        da.Fill(dt);

  

        return dt;

    }

  

    public DataTable fnSelectUserById(DatabaseLayer objDL)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "spSelectUserById";

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Connection = con;

  

        cmd.Parameters.AddWithValue("@ID", objDL.ID);

  

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();

        da.Fill(dt);

  

        return dt;

    }

  

    public int fnUpdate(DatabaseLayer objDL)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "spUpdate";

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Connection = con;

  

        cmd.Parameters.AddWithValue("@ID", objDL.ID);

        cmd.Parameters.AddWithValue("@FullName", objDL.FullName);

        cmd.Parameters.AddWithValue("@EmailAddress", objDL.EmailAddress);

        cmd.Parameters.AddWithValue("@Password", objDL.Password);

        cmd.Parameters.AddWithValue("@Gender", objDL.Gender);

        cmd.Parameters.AddWithValue("@Hobbies", objDL.Hobbies);

        cmd.Parameters.AddWithValue("@ProfilePic", objDL.ProfilePic);

  

        con.Open();

        int isUpdated = cmd.ExecuteNonQuery();

        con.Close();

  

        return isUpdated;

    }

  

    public void fnDelete(DatabaseLayer objDL)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "spDelete";

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Connection = con;

  

        cmd.Parameters.AddWithValue("@ID", objDL.ID);

  

        con.Open();

        cmd.ExecuteNonQuery();

        con.Close();

    }

}

How to add database to Visual Studio and taking Connection String? : To add database from MS SQL Server to your Visual Studio you need to follow these steps. Open Database Explorer -> Right Click on Data Connection -> Click on Add Connection -> Write Server name (You can copy server name from MS SQL Server. It will display when you connect to SQL Server) -> Select or enter database name (Your database name) -> Click ok. Now take a Connection String from property of your connected database in Database Explorer.

Business Logic Layer

This layer is simply a code behind file of your .aspx page. Write code in it to connect it with database layer.

Insert Operation

Step 1. Now it’s time to write code for inserting data. Get a click event of Insert button. As you double click on button you get switched to Default.aspx.cs file which is a code behind file of Default.aspx. Here write code in C# for inserting data.

Step 2. First create object of DatabaseLayer to access its property and methods.

DatabaseLayer objDL = new DatabaseLayer();

Step 3. Now write a code to pass values from business layer to database layer. Below is the code.

Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page

{

    /* Create object of database layer to access its property and methods */

    DatabaseLayer objDL = new DatabaseLayer();

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void btnInsert_Click(object sender, EventArgs e)

    {

        /* Assigning values to variables */

        string Gender = "", Hobbies = "", FileName = "", Path = "", FullPath = "";

        if (rdoMale.Checked == true)

        {

            Gender = rdoMale.Text;

        }

        if (rdoFemale.Checked == true)

        {

            Gender = rdoFemale.Text;

        }

        if (chkCricket.Checked == true)

        {

            if (Hobbies == "")

            {

                Hobbies = chkCricket.Text;

            }

            else

            {

                Hobbies = Hobbies + "," + chkCricket.Text;

            }

        }

        if (chkFootball.Checked == true)

        {

            if (Hobbies == "")

            {

                Hobbies = chkFootball.Text;

            }

            else

            {

                Hobbies = Hobbies + "," + chkFootball.Text;

            }

        }

        if (fileProfilePic.HasFile)

        {

            FileName = fileProfilePic.FileName;

            Path = Server.MapPath("profilepic"); /* Create a folder with profilepic in webiste */

            FullPath = Path + "//" + FileName;

            fileProfilePic.SaveAs(FullPath);

        }

        /* Assigning variable values to Property */

        objDL.FullName = txtFullName.Text;

        objDL.EmailAddress = txtEmailAddress.Text;

        objDL.Password = txtPassword.Text;

        objDL.Gender = Gender;

        objDL.Hobbies = Hobbies;

        objDL.ProfilePic = FileName;

        /* Calling DatabaseLayer method and passing value to it */

        int isInserted = objDL.fnInsert(objDL);

        if (isInserted > 0)

        {

            lblMsg.Text = "Inserted Successfully..!!";

        }

        else

        {

            lblMsg.Text = "Erro Inserting Data..!!";

        }

    }

}

Step 4. Run the Default.aspx page. Enter data to all fields and click Insert button. Data will be inserted to tale and “Inserted Successfully..!!” message will display.

Step 5. Check your inserted data in table. MS SQL Server -> Right click on table -> Select Top 1000 Rows.

Select Operation

Step 1. Now add new page ShowData.aspx to make GridView and perform Select operation. Add page, drag and drop GridView and see given code to design it. You will find GridView in Data tab of Tollbox.

ShowData.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowData.aspx.cs" Inherits="ShowData" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Show Data</title>

    <style type="text/css">

        .clsmargin {

            margin: 0 auto 15px;

            display: table;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div class="clsmargin" style="margin-top: 5%">

            <h2 class="clsmargin">Show Data Form</h2>

            <asp:GridView ID="grdView" runat="server" AutoGenerateColumns="false" OnRowCommand="grdView_RowCommand">

                <Columns>

                    <asp:TemplateField HeaderText="ID">

                        <ItemTemplate>

                            <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Full Name">

                        <ItemTemplate>

                            <asp:Label ID="lblFullName" runat="server" Text='<%#Eval("FullName") %>'></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Email Address">

                        <ItemTemplate>

                            <asp:Label ID="lblEmailAddress" runat="server" Text='<%#Eval("EmailAddress") %>'></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Password">

                        <ItemTemplate>

                            <asp:Label ID="lblPassword" runat="server" Text='<%#Eval("Password") %>'></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Gender">

                        <ItemTemplate>

                            <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Hobbies">

                        <ItemTemplate>

                            <asp:Label ID="lblHobbies" runat="server" Text='<%#Eval("Hobbies") %>'></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Profile Picture">

                        <ItemTemplate>

                            <asp:Image ID="imgProfilePicture" runat="server" ImageUrl='<%# "profilepic/" + Eval("ProfilePic") %>' Style="height: 50px; width: 50px"></asp:Image>

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Actions">

                        <ItemTemplate>

                            <asp:LinkButton ID="lnkbtnEdit" CommandName="lnkbtnEdit" CommandArgument='<%#Eval("ID") %>' runat="server">Edit</asp:LinkButton>

                            <asp:LinkButton ID="lnkbtnDelete" CommandName="lnkbtnDelete" CommandArgument='<%#Eval("ID") %>' runat="server">Delete</asp:LinkButton>

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

            </asp:GridView>

        </div>

    </form>

</body>

</html>

Step 2. Now write C# code to bind GridView. Open ShowData.aspx.cs file, create getData() function to write code for database connectivity and call this function in Page_Load() event of ShowData.aspx.cs.

ShowData.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

  

public partial class ShowData : System.Web.UI.Page

{

    DatabaseLayer objDL = new DatabaseLayer();

  

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            getData();

        }

    }

  

    /* Bind GridView */

    public void getData()

    {

        grdView.DataSource = objDL.fnSelect();

        grdView.DataBind();

    }

  

    /* Row command event - calling when user click on edit or delete button */

    protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        /* This condition work when click on edit button */

        if (e.CommandName == "lnkbtnEdit")

        {

            int id = int.Parse(e.CommandArgument.ToString());

            Response.Redirect("UpdateData.aspx?id=" + id); /* Pass id in querystring for updating record */

        }

  

        /* This condition work when click on delete button */

        if (e.CommandName == "lnkbtnDelete")

        {

            objDL.ID = int.Parse(e.CommandArgument.ToString());

            objDL.fnDelete(objDL);

            getData();

        }

    }

}

In above code getData() function is used to bind gridview with database records. grdView_RowCommand() event is called when the user clicks on Edit or Delete button. The event is Edit or Delete that is recognized by e.CommandName. And e.CommandArgument is used to get id of the row on which the user has clicked. When the user clicks on Edit link button, it will be redirected to update the page with Query String to update clicked record and click of Delete button will delete the record and rebind gridview.

Step 3. Run ShowData.aspx page and you will see GridView with data having in table. As you see there are Edit and Delete buttons are available for doing edit and delete operations.

Update Operation

Step 1. Create new page UpdateData.aspx. This page will look same as insert form but the difference is the controls should be prefilled with user data on which the user has clicked on edit button in gridview. Data will be fetched on load event using id sent from ShoData.aspx page in URL using Query String.

UpdateData.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpdateData.aspx.cs" Inherits="UpdateData" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Update</title>

    <style type="text/css">

        table tr td {

            border: 1px solid #CACFD2;

        }

        table {

            margin: 0 auto;

        }

        .clsmargin {

            margin: 0 auto 15px;

            display: table;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server" class="mar-top-10">

        <div style="margin-top: 10%">

            <h2 class="clsmargin">Update Form</h2>

            <table>

                <tr>

                    <td>Full Name

                    </td>

                    <td>

                        <asp:TextBox ID="txtFullName" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Email Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Password

                    </td>

                    <td>

                        <asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Gender

                    </td>

                    <td>

                        <asp:RadioButton ID="rdoMale" Text="Male" GroupName="Gender" runat="server" />

                        <asp:RadioButton ID="rdoFemale" Text="Female" GroupName="Gender" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Hobbies

                    </td>

                    <td>

                        <asp:CheckBox ID="chkCricket" Text="Cricket" runat="server" />

                        <asp:CheckBox ID="chkFootball" Text="Football" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Profile Picture

                    </td>

                    <td>

                        <asp:Image ID="imgUser" runat="server" Style="height: 50px; width: 50px" />

                        <br />

                        <asp:FileUpload ID="fileProfilePic" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Button Text="Update" ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" />

                        <asp:Button Text="Cancel" ID="btnCancel" runat="server" OnClick="btnCancel_Click" />

                    </td>

                </tr>

            </table>

            <h4 class="clsmargin">

                <asp:Label Text="" ID="lblMsg" runat="server" Style="color: green" />

            </h4>

            <asp:HiddenField ID="hdImageName" runat="server" />

        </div>

    </form>

</body>

</html>

UpdateData.aspx.cs

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

  

public partial class UpdateData : System.Web.UI.Page

{

    DatabaseLayer objDL = new DatabaseLayer();

  

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            if (Request.QueryString["id"] != null)

            {

                getUserById();

            }

            else

            {

                Response.Redirect("ShowData.aspx");

            }

        }

    }

  

    /* Get user data by userid */

    public void getUserById()

    {

        objDL.ID = int.Parse(Request.QueryString["id"].ToString());

        DataTable dt = objDL.fnSelectUserById(objDL); /* Select User by Id method of Database Layer */

  

        txtFullName.Text = dt.Rows[0]["FullName"].ToString();

        txtEmailAddress.Text = dt.Rows[0]["EmailAddress"].ToString();

        txtPassword.Attributes.Add("value", dt.Rows[0]["Password"].ToString());

        if (dt.Rows[0]["Gender"].ToString() == "Male")

        {

            rdoMale.Checked = true;

        }

        if (dt.Rows[0]["Gender"].ToString() == "Female")

        {

            rdoFemale.Checked = true;

        }

        string[] Hobbies = dt.Rows[0]["Hobbies"].ToString().Split(',');

        for (int i = 0; i < Hobbies.Length; i++)

        {

            if (Hobbies[i] == "Cricket")

            {

                chkCricket.Checked = true;

            }

            if (Hobbies[i] == "Football")

            {

                chkFootball.Checked = true;

            }

        }

        imgUser.ImageUrl = "profilepic/" + dt.Rows[0]["profilepic"].ToString();

        hdImageName.Value = dt.Rows[0]["profilepic"].ToString();

    }

  

    /* Update Code */

    protected void btnUpdate_Click(object sender, EventArgs e)

    {

        string Gender = "", Hobbies = "", FileName = "", Path = "", FullPath = "";

        if (rdoMale.Checked == true)

        {

            Gender = rdoMale.Text;

        }

        if (rdoFemale.Checked == true)

        {

            Gender = rdoFemale.Text;

        }

        if (chkCricket.Checked == true)

        {

            if (Hobbies == "")

            {

                Hobbies = chkCricket.Text;

            }

            else

            {

                Hobbies = Hobbies + "," + chkCricket.Text;

            }

        }

        if (chkFootball.Checked == true)

        {

            if (Hobbies == "")

            {

                Hobbies = chkFootball.Text;

            }

            else

            {

                Hobbies = Hobbies + "," + chkFootball.Text;

            }

        }

        if (fileProfilePic.HasFile)

        {

            FileName = fileProfilePic.FileName;

            Path = Server.MapPath("profilepic");

            FullPath = Path + "//" + FileName;

            fileProfilePic.SaveAs(FullPath);

        }

        else

        {

            FileName = hdImageName.Value;

        }

  

        objDL.ID = int.Parse(Request.QueryString["id"].ToString());

        objDL.FullName = txtFullName.Text;

        objDL.EmailAddress = txtEmailAddress.Text;

        objDL.Password = txtPassword.Text;

        objDL.Gender = Gender;

        objDL.Hobbies = Hobbies;

        objDL.ProfilePic = FileName;

  

        /* Calling DatabaseLayer method and passing value to it */

        int isUpdated = objDL.fnUpdate(objDL);

        if (isUpdated > 0)

        {

            Response.Redirect("ShowData.aspx");

        }

        else

        {

            lblMsg.Text = "Erro Inserting Data..!!";

        }

    }

  

    /* Cancel Code */

    protected void btnCancel_Click(object sender, EventArgs e)

    {

        Response.Redirect("ShowData.aspx");

    }

}

Step 2. Run the page and you will see the page like below. Update data and check it will reflect in gridview.

Delete Operation

To perform delete operation we do not have to create new page because it is already done in ShowData.aspx page on Delete button click event. Please see my ShowData.aspx.cs page for delete button code, it is written in grdView_RowCommand() event.

/* Row command event - calling when user click on edit or delete button */

protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)

{

    /* This condition work when click on edit button */

    if (e.CommandName == "lnkbtnEdit")

    {

        int id = int.Parse(e.CommandArgument.ToString());

        Response.Redirect("UpdateData.aspx?id=" + id); /* Pass id in querystring for updating record */

    }

  

    /* This condition work when click on delete button */

    if (e.CommandName == "lnkbtnDelete")

    {

        objDL.ID = int.Parse(e.CommandArgument.ToString());

        objDL.fnDelete(objDL);

        getData();

    }

}

Run the page and check all operations. Hope you will like this blog. Feel free to ask question. Thanks You… :)