Click here to Skip to main content
11,702,130 members (62,982 online)
Click here to Skip to main content

Insert, Update, Delete with Gridview ... Simple Way

, 4 Mar 2008 CPOL 329.7K 17.8K 69
Rate this:
Please Sign up or sign in to vote.
This is a simple way to Insert, Update, Delete and Display through a single page.

InsertingWithGridView/3.gif

Introduction

This is a simple way to display, Update, Delete and Insert through a single page.

Using the Code

Many of us may be encountered with Update and Delete operations with GridView. I’m explaining this with more functionality that is Inserting record through the GridView. There could me more way to achieve this functionality but I think it’s a very simple way to achieve this. I’m taking a very simple table named "quest_categories"

InsertingWithGridView/Table.gif

CREATE TABLE [dbo].[quest_categories](
    [cat_id] [int] IDENTITY(1,1) NOT NULL,
    [cat_name] [varchar](150) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 CONSTRAINT [PK_quest_categories] PRIMARY KEY CLUSTERED 
(
    [cat_id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Here is the GridView that is going to perform the operation for Insert, Update and Delete the Data. Here I’ve added a Button "Add Category" for inserting a new record.

InsertingWithGridView/1.gif

Here is the Code for "Add Category"

protected void btnAdd_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["exam_moduleConnectionString"].ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter("SELECT cat_id, cat_name FROM quest_categories", con);
    DataTable dt = new DataTable();
    da.Fill(dt);

    // Here we'll add a blank row to the returned DataTable
    DataRow dr = dt.NewRow();
    dt.Rows.InsertAt(dr, 0);
    //Creating the first row of GridView to be Editable
    GridView1.EditIndex = 0;
    GridView1.DataSource = dt;
    GridView1.DataBind();
    //Changing the Text for Inserting a New Record
    ((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";

}

After Clicking on "Add Category" the GridView will diplay like this. InsertingWithGridView/3.gif

And according to Text Diplays we’ll do further processing as "Update" or "Insert" record.

Here is the code for "RowUpdating" event.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        if (((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text == "Insert")
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["exam_moduleConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO quest_categories(cat_name) VALUES(@cat_name)";
            cmd.Parameters.Add("@cat_name", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[0].Cells[2].Controls[0]).Text;

            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
        else
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["exam_moduleConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "UPDATE quest_categories SET cat_name=@cat_name WHERE cat_id=@cat_id";
            cmd.Parameters.Add("@cat_name", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
            cmd.Parameters.Add("@cat_id", SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            
        }


        GridView1.EditIndex = -1;
        BindData();
    }

Rest operations are same as you might have done before so I’m not explaining it further.

InsertingWithGridView/2.gif

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

rahul_bit
Web Developer TATA Communications
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionMy vote is 3 Pin
Ashish Ramteke7-Jan-14 6:37
memberAshish Ramteke7-Jan-14 6:37 
GeneralColumn Type error Pin
rf_libra28-Jun-13 22:17
memberrf_libra28-Jun-13 22:17 
Questionfgfdgdg Pin
Member 85264792-Jun-13 8:50
memberMember 85264792-Jun-13 8:50 
Suggestionnice article Pin
Ashutosh19625-Apr-13 19:19
memberAshutosh19625-Apr-13 19:19 
QuestionMy vote of 5 Pin
Alireza_136217-Apr-13 20:40
memberAlireza_136217-Apr-13 20:40 
GeneralMy vote of 3 Pin
supriya chaladi19-Mar-13 21:44
membersupriya chaladi19-Mar-13 21:44 
Questionthank Pin
pusue15-Sep-12 0:22
memberpusue15-Sep-12 0:22 
Questioncomment Pin
Member 885114316-May-12 19:36
memberMember 885114316-May-12 19:36 
Questioncshtml Pin
Member 89490539-May-12 1:02
memberMember 89490539-May-12 1:02 
QuestionNeed enhancement of form ? Pin
Member 388846130-Apr-12 0:43
memberMember 388846130-Apr-12 0:43 
QuestionInsert, Update, Delete with Gridview Pin
swarup2629-Apr-12 21:28
memberswarup2629-Apr-12 21:28 
Generalthanks...! Pin
vinay_2897-Apr-12 1:23
membervinay_2897-Apr-12 1:23 
QuestionThank you! Pin
Member 211582631-Jan-12 11:49
memberMember 211582631-Jan-12 11:49 
GeneralMy vote of 5 Pin
hyderalima15-Sep-11 1:28
memberhyderalima15-Sep-11 1:28 
GeneralMy vote of 5 Pin
Monjurul Habib2-Mar-11 9:20
memberMonjurul Habib2-Mar-11 9:20 
GeneralMy vote of 5 Pin
dwyman17-Feb-11 11:48
memberdwyman17-Feb-11 11:48 
GeneralFor Select,Insert,Update and Delete in GridView without writting C# or Vb Code Pin
vijay_vignesh26-Jan-11 1:24
membervijay_vignesh26-Jan-11 1:24 
GeneralMy vote of 1 Pin
sang15th525-Nov-10 5:59
membersang15th525-Nov-10 5:59 
GeneralRow updation in a grid view [modified] Pin
rekha bothiraj15-Oct-10 4:22
memberrekha bothiraj15-Oct-10 4:22 
GeneralMy vote of 4 Pin
vnkb5-Aug-10 20:27
membervnkb5-Aug-10 20:27 
Generalthrown error Pin
kanimozhi.A1-Jun-10 20:04
memberkanimozhi.A1-Jun-10 20:04 
GeneralThank's a lot Pin
rudyswardani3-Apr-10 0:42
memberrudyswardani3-Apr-10 0:42 
Thanks a lot, simple exemple but very clear to understand
GeneralI can't execute your example Pin
troy7118-Mar-10 15:32
membertroy7118-Mar-10 15:32 
GeneralThaks A Lot Pin
Abinash Bishoyi12-Jan-10 20:13
memberAbinash Bishoyi12-Jan-10 20:13 
QuestionMay i Know meaning of the Line Pin
sakthipriya843-Dec-09 1:16
membersakthipriya843-Dec-09 1:16 
GeneralGreat Pin
Amjad_pk27-Oct-09 18:32
memberAmjad_pk27-Oct-09 18:32 
GeneralThe article is good Pin
swapniljakkulwar6-Aug-09 19:45
memberswapniljakkulwar6-Aug-09 19:45 
GeneralThis is excellent solution Pin
ftrghuy13-May-09 0:25
memberftrghuy13-May-09 0:25 
QuestionHow do you handle cancel? Pin
doran_doran23-Mar-09 11:28
memberdoran_doran23-Mar-09 11:28 
GeneralThanks! Pin
pap200519-Feb-09 12:35
memberpap200519-Feb-09 12:35 
GeneralGood Article Pin
kjelltj26-Jan-09 3:33
memberkjelltj26-Jan-09 3:33 
Generalgood one Pin
v.jayakrishnan10-Jan-09 8:06
memberv.jayakrishnan10-Jan-09 8:06 
GeneralSome more resources on GridView here Pin
Sheo Narayan3-Jul-08 6:49
memberSheo Narayan3-Jul-08 6:49 
Generalpoor article Pin
madhunangeth26-Jun-08 1:33
membermadhunangeth26-Jun-08 1:33 
GeneralGood Article Pin
ComputerAngel1-Jun-08 7:57
memberComputerAngel1-Jun-08 7:57 
GeneralIt doesn’t work correctly!!! Pin
docsoft24-Mar-08 10:05
memberdocsoft24-Mar-08 10:05 
GeneralBest Article Pin
Manish_Jaanvi4-Mar-08 2:12
memberManish_Jaanvi4-Mar-08 2:12 
GeneralRe: Best Article Pin
Dewey4-Mar-08 13:35
memberDewey4-Mar-08 13:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150819.1 | Last Updated 4 Mar 2008
Article Copyright 2008 by rahul_bit
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid