This blog will explain you how to create web application and performing CRUD (Create, Read, Update and Delete) operation (You can also say Insert, Select, Update and Delete operations.) in ASP.NET GridView using single tier. Single tier means the all code has been written in single .cs file.

Follow the steps to perform operation.

Create Empty Web Site

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\CRUDOperation” and click OK.

If you has been asked for “folder does not exist. Would you like to create this folder?” then your website folder is not available. So click Yes button to create new folder for website.

An empty web site has been created.

Step 5. Now open “Solution Explorer”. You can see one configuration file named web.config is already available in solution explorer which shows particular web site related configuration such as targetFramework="4.5". If you can’t find solution explorer open it from toolbar as VIEW->Solution Explorer.

Create Database and Table

Step 1. Right click on your website and select Add New Item to add SQL Server Database.

Step 2. After clicking Add New Item, you will see list. Select “SQL Server Database” and click on Add button. You can change database name. I have changed to CRUD.mdf. The extension of database file is “.mdf”. Then studio will ask to place database to “App_Data” folder. Click yes to set database file separate from other files of project.

As you add database, you will see CRUD.mdf file in App_Data folder in Solution Explorer and database created in Database Explorer.

Step 3. To create a table, expand database in Database Explorer and right click on Table folder and select Add New Table.

Step 4. Design table as show in below image. Add columns as per requirement.

Step 5. Set int data type to ID column and then set Primary Key to it. Right click to ID column and select Set Primary Key. You will see key symbol at left of ID column. 

Step 6. Make ID column Auto Increment by right clicking on ID column and select Property option. From the property window expand Identity Specification property and set IsIdentity to True, which will make ID column auto increment.

Step 7. Now change table name from T-SQL window. Please see image to do this step. Then click on Update button and then click Update Database.

Note: If you are using Visual Studio 2010, then press Ctrl+s to save table. 

Table is created now. Refresh Table folder to see your table.

Design Web Page

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

Step 2. After clicking Add New Item, you will see list. Select “Web Form” and click on Add button. Please set selection to C# at left panel while adding web form. Make you first page with name Default.aspx. Page has been added to Solution Explorer.

Step 3. Now design form to insert data. Take fields according to our database. As ID in 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 runat="server">

    <title></title>

    <style type="text/css">

        table tr td {

            border: 1px solid #CACFD2;

        }

        table {

            margin: 10% auto 0;

        }

        .clsmargin {

            margin: 0 auto 15px;

            display: table;

        }

    </style>

</head>

<body>

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

        <div>

            <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" />

                    </td>

                </tr>

            </table>

            <h4 class="clsmargin">

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

            </h4>

</div>

    </form>

</body>

</html>

You can drag and drop controls from toolbox. If you can’t find toolbox open it from toolbar as VIEW->Toolbox.

Step 4. As your design completed, run page to browser. Right click to Default.aspx page in Solution Explorer and select View in Browser.

Your form will look like below.

Insert Operation

Step 1. Now it’s time to write code for inserting data. Right now you are in the Source tab of Default.aspx, switch to Design tab and Take a click event of button by double clicking on button.

As you double click on button you got 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 add two namespaces at top of the page

using System.Data.SqlClient;

using System.Data;

Step 3. Take a Connection String to connect with database. Follow the step.

Right click on your database from Database Explorer-> Open its property-> Find Connection String property-> Copy its whole string and paste it to strCon variable.

Also create a folder with name profilepic in Solution Explorer.

Step 4. After then write insert code in btnInsert_Click event.

Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

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

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

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

{

    /* Connection String */

    string strCon = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ Desktop\CRUDOperation\App_Data\CRUD.mdf;Integrated Security=True";

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void btnInsert_Click(object sender, EventArgs e)

    {

        /* Insert Code */

        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);

        }

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand("insert into tblCRUD(FullName,EmailAddress,Password,Gender,Hobbies,ProfilePic) values('" + txtFullName.Text + "','" + txtEmailAddress.Text + "','" + txtPassword.Text + "','" + Gender + "','" + Hobbies + "','" + FileName + "')", con);

        con.Open();

        int isInserted = cmd.ExecuteNonQuery();

        con.Close();

        if (isInserted > 0)

        {

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

        }

        else

        {

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

        }

    }

}

Step 5. 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 6. Check your inserted data in table. Open table by right click on table-> select Show Table Data.

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;

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

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

  

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

{

    /* Connection String */

    string strCon = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users \Desktop\CRUDOperation\App_Data\CRUD.mdf;Integrated Security=True";

  

    /* Page load event */

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            getData();

        }

    }

  

    /* Bind GridView */

    public void getData()

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlDataAdapter da = new SqlDataAdapter("select * from tblCRUD", con);

        DataTable dt = new DataTable();

        da.Fill(dt);

        grdView.DataSource = dt;

        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")

        {

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

            SqlConnection con = new SqlConnection(strCon);

            SqlCommand cmd = new SqlCommand("delete from tblCRUD where ID='" + id + "'", con);

            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();

            getData(); /* Reload gridview */

        }

    }

}

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">

        <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>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.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

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

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

  

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

{

    /* Connection String */

    string strCon = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users \Desktop\CRUDOperation\App_Data\CRUD.mdf;Integrated Security=True";

  

    /* Page load event */

    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()

    {

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

        SqlConnection con = new SqlConnection(strCon);

        SqlDataAdapter da = new SqlDataAdapter("select * from tblCRUD where id='" + id + "'", con);

        DataTable dt = new DataTable();

        da.Fill(dt);

  

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

        txtEmailAddress.Text = dt.Rows[0]["EmailAddress"].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)

    {

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

        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;

        }

  

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand("update tblCRUD set FullName='" + txtFullName.Text + "',EmailAddress='" + txtEmailAddress.Text + "',Gender='" + Gender + "',Hobbies='" + Hobbies + "',ProfilePic='" + FileName + "' where ID='" + id + "'", con);

        con.Open();

        int isUpdated = cmd.ExecuteNonQuery();

        con.Close();

        if (isUpdated > 0)

        {

            Response.Redirect("ShowData.aspx");

        }

        else

        {

            lblMsg.Text = "Erro Updating 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.

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")

    {

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

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand("delete from tblCRUD where ID='" + id + "'", con);

        con.Open();

        cmd.ExecuteNonQuery();

        con.Close();

        getData(); /* Reload gridview */

    }

}

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