Insert, Update, Delete In GridView Using ASP.Net C#

Background

Sometimes there is a need to insert, update and delete records in a GridView using a single Stored Procedure instead of creating separate Stored Procedures for each operation.

Suppose I have one .aspx web page in which I need a to insert, view, update and delete records. To do that, instead of creating four Stored Procedures to perform these tasks I will create a single Stored Procedure to satisfy my requirements and I will access it in code behind depending on the action performed by the end user on a button click.

I have written this article especially focusing on newcomers and anyone new wants to insert, update and delete records in a GridView using a Single Stored Procedure, so let us start with a basic introduction.

First create the table named employee as:

creatingtbl.png

I have set the primary key on the id column and I have set the Identity specification to Yes.

Now we have a table to perform these operations for. Now let us start to create the Stored Procedure.

The Stored Procedure is created using the keyword "Create Procedure" followed by the procedure name. Let us create the Stored Procedure named "EmpEntry" as in the following:

  1. create Procedure EmpEntry  
  2. (  
  3.   --variable  declareations   
  4.  @Action Varchar (10),    --to perform operation according to string ed to this varible such as Insert,update,delete,select        
  5.  @id int=null,    --id to perform specific task  
  6.  @FnameVarchar (50)=null,   -- for FirstName  
  7.  @MName Varchar (50)=null,   -- for MName  
  8.  @Lname Varchar (50)=null    -- for LastName  
  9. )  
  10. as  
  11. Begin   
  12.   SET NOCOUNT ON;  
  13.   
  14. If @Action='Insert'   --used to insert records  
  15. Begin  
  16.    Insert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)  
  17. End    
  18. else if @Action='Select'   --used to Select records  
  19. Begin  
  20.     select *from employee  
  21. end  
  22. else if @Action='Update'  --used to update records  
  23. Begin  
  24.    update employeeset FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id  
  25.  End  
  26.  Else If @Action='delete'  --used to delete records  
  27.  Begin  
  28.    delete from employeewhere id=@id  
  29.  end  
  30. End  
The comments in the Stored Procedure above clearly explain which block is used for which purpose, so I have briefly explained it again. I have used the @Action variable and assigned the string to them and according to the parameter ed to the Stored Procedure the specific block will be executed because I have kept these blocks or conditions in nested if else if conditional statements.

Now create the one sample application "Empsys" as:

  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as  "Empsys" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - "Default.aspx page".
  5. Drag and drop one button, three textboxes, one GridView and one hidden field to the hidden value to the database and one label on the <form> section of the Default.aspx page.

Then switch to the design view; the <form> section of the Default aspx page source will look as in the following:

  1. <form id="form1"runat="server">  
  2.     <div>  
  3. First Name  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  4. Middle Name<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  5. Last Name <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>  
  6.         <asp:ButtonIDasp:ButtonID="Button1"runat="server"Text="save"onclick="Button1_Click" />  
  7.     </div>  
  8. <asp:HiddenField ID="HiddenField1" runat="server"/>  
  9.  <asp:GridViewIDasp:GridViewID="GridView1"runat="server" >  
  10.      </asp:GridView>  
  11. </form>  

Now use the following GridView event properties to perform events such as update, delete, edit cancel and so on. Let us see what the properties are:

  • DataKeyNames: This property I have used to the row index of GridView  
  • OnRowEditing: This property is used to handle the event when the user clicks on the edit button
  • OnRowCancelingEdit: This property is used to handle the event when the user clicks on the Cancel button that exists after clicking on the edit button
  • OnRowDeleting: This property is used to handle the event when the user clicks on the delete button that deletes the row of the GridView
  • OnRowUpdating: This property is used to handle the event when the user clicks on the update button that updates the Grid Record 

Now my grid will look such as the following:

  1. <asp:GridViewIDasp:GridViewID="GridView1" runat="server" DataKeyNames ="id"OnRowEditing ="Edit"                 
  2.         OnRowCancelingEdit ="canceledit"    OnRowDeleting ="delete"    OnRowUpdating = "Update" >  
  3. </asp:GridView>  

On the preceding GridView properties I have assigned the method name to be called for particular operations.

Method to Insert Data in Database  

Right-click from the design page and view the code and then write the following code in the default.aspx.cs page to save the inserted records in the database:

  1. protected void empsave(object sender, EventArgs e)  
  2. {  
  3.       connection();  
  4.       query =  "studentEntryView";          //Stored Procedure name   
  5.       SqlCommand com = new SqlCommand(query, con);  //creating  SqlCommand  object  
  6.       com.CommandType = CommandType.StoredProcedure;  //here we declaring command type as stored Procedure  
  7.   
  8.        /* adding paramerters to  SqlCommand below *\  
  9.       com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();//for ing hidden value to preform insert operation  
  10.        com.Parameters.AddWithValue("@FName",TextBox1.Text.ToString());        //first Name  
  11.        com.Parameters.AddWithValue("@Mname ", TextBox2.Text.ToString());     //middle Name  
  12.        com.Parameters.AddWithValue("@LName ",TextBox3.Text.ToString());       //Last Name  
  13.        com.ExecuteNonQuery();                     //executing the sqlcommand  
  14.        Label1.Visible = true;  
  15.        Label1.Text = "Records are Submitted Successfully";  
  16. }  
Now create the mehtod to view the records in the GridView:
  1. public void viewdata()  
  2. {  
  3.     connection();  
  4.     query = "studentEntryView";  
  5.     SqlCommand com = new SqlCommand(query, con);  
  6.     com.CommandType = CommandType.StoredProcedure;  
  7.     com.Parameters.AddWithValue("@Action", HiddenField2.Value).ToString();  
  8.     DataSet ds =new DataSet();  
  9.     SqlDataAdapter da =  new SqlDataAdapter(com);  
  10.     da.Fill(ds);  
  11.     GridView1.DataSource = ds;  
  12.     GridView1.DataBind();  
  13. }  
The following is method for the "OnRowEditing" Event:
  1. protected void edit(objectsender, GridViewEditEventArgs e)  
  2. {  
  3.     GridView1.EditIndex= e.NewEditIndex;  
  4.     gedata();  
  5. }  
The following is method for the "OnRowCancelingEdit" Event:
  1. protected void  canceledit(object sender, GridViewCancelEditEventArgs e)  
  2. {  
  3.     GridView1.EditIndex = -1;  
  4.     gedata();  
  5. }  
The following is method for the "OnRowDeleting" Event:
  1. protected void delete(object sender, GridViewDeleteEventArgs e)  
  2. {  
  3.       connection();  
  4.       int id =  int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  
  5.       HiddenField1.Value = "Delete";  
  6.       query = "EmpEntry";  
  7.       com = new SqlCommand(query, con);  
  8.       com.CommandType =CommandType .StoredProcedure;  
  9.       com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();  
  10.       com.Parameters.AddWithValue("id", SqlDbType.Int).Value = id;  
  11.       com.ExecuteNonQuery();  
  12.       con.Close();  
  13.       gedata();  
  14. }  
The following is method for the "OnRowUpdating" Event:
  1. protected void update(object sender, GridViewUpdateEventArgs e)  
  2. {  
  3.      connection();  
  4.      int id=int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  
  5.      HiddenField1.Value = "update";  
  6.      query = "EmpEntry";  
  7.      com = new SqlCommand(query, con);  
  8.      com.CommandType = CommandType.StoredProcedure;  
  9.      com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();  
  10.      com.Parameters.AddWithValue("@FName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());  
  11.      com.Parameters.AddWithValue("@MName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());  
  12.      com.Parameters.AddWithValue("@LName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());  
  13.      com.Parameters.AddWithValue("@id", SqlDbType.int ).Value = id;  
  14.      com.ExecuteNonQuery();  
  15.      con.Close();  
  16.      GridView1.EditIndex = -1;  
  17.      gedata();  
  18. }  
Brief introduction to the code

In the sample code above I have used the two string queries for giving the Stored Procedure name and the constr for storing the connection from the web.config file and another thing is that I have used a hidden field by which I am ing the action values that are required to our Stored Procedure.

Now our application is ready to use, press F5 or other as you know, then enter the some values to TextBox and press the "Save" button.

insertform.png

Now after clicking on the "Save" button, the hidden field value takes the value "Insert" and es it to the Stored Procedure as the action and because of this the Stored Procedure will execute a particular type of block.

Now at page load I have called the method, so after that the grid will fill as in:

rcoraddedingrid.png

Now click on the Edit button that calls the edit method as shown in the following grid:

editview.png

If you click on the "Cancel" button then the editcancel method will be called and edit mode will be cancelled. Now enter some values into the grid TextBox and click on an update button that calls the update method and then the records in the GridView will be updated as in:

Griafterupdate.png

Now click on the delete button that calls the delete method and deletes the records from the GridView

Note
  • For detailed code please download the zip file attached above.
  • Don't forget to update the Web.config file for your server location. 
Summary
 
From all the examples above we see how to reduce the code required to perform these tasks. In the next article, I will explain how to Implement a 2-tier architecture which makes my code much simpler and reusable, I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.


Similar Articles