home » articles » Adding Rows in GridView with Edit, Update and Delete Functionality

Adding Rows in GridView with Edit, Update and Delete Functionality

change text size: A A A

6/10/2009 by Vinz

This example is a continuation of my previous post about “Adding Rows in GridView”. In this example will going to demonstrate on how we are going to do Edit, Update and Delete operations in GridView using TemplateField Columns. If you wan’t to implement those operations using BoundField Columns then you can refer to my previous example about “GridView: Insert, Edit, Update and Delete – the ADO.NET way”.

Since this example is a continuation, then I would recommend you to start reading this example first before you proceeds reading this example.

Now let’s set up our GridView to allow editing of Rows. Since we are not using BoundFields in this example then we need to set up our own Edit fields using EditItemTemplate. See the mark up below:

<asp:GridView ID="GridViewEmployee" runat="server" AutoGenerateColumns="False"

ShowFooter="True" onrowcancelingedit="GridViewEmployee_RowCancelingEdit"

onrowediting="GridViewEmployee_RowEditing"

onrowupdating="GridViewEmployee_RowUpdating">

<Columns>

<asp:TemplateField HeaderText="Employee Name">

<EditItemTemplate>

<asp:TextBox ID="TextBoxEditEmployee" runat="server" Text='<%# Bind("Employees") %>'/>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="LabelEmployee" runat="server" Text='<%# Bind("Employees") %>'/>

</ItemTemplate>

<FooterTemplate>

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

</FooterTemplate>

</asp:TemplateField >

<asp:TemplateField HeaderText="Position">

<EditItemTemplate>

<asp:TextBox ID="TextBoxEditPosition" runat="server" Text='<%# Bind("Position") %>'/>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="LabelPosition" runat="server" Text='<%# Bind("Position") %>'/>

</ItemTemplate>

<FooterTemplate>

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

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Team Name">

<EditItemTemplate>

<asp:TextBox ID="TextBoxEditTeam" runat="server" Text='<%# Bind("Team") %>'/>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="LabelTeam" runat="server" Text='<%# Bind("Team") %>'/>

</ItemTemplate>

<FooterTemplate>

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

</FooterTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Employee ID">

<ItemTemplate>

<asp:Label ID="LabelID" runat="server" Text='<%# Bind("Id") %>'/>

</ItemTemplate>

<FooterTemplate>

<asp:Button ID="Button1" runat="server" Text="Add New" OnClick="Button1_Click" />

</FooterTemplate>

</asp:TemplateField>

<asp:CommandField ShowEditButton="True" />

</Columns>

</asp:GridView>

Notice that under EditItemTemplate, we added a TextBox control for each column. These columns will be shown once we set the GridView to edit mode. Now let’s create the methods first for updating the GridView data.

Here’s the code block below:

private void UpdateRecord(string id,string employee, string position, string team)

{

SqlConnection connection = new SqlConnection(GetConnectionString());

string sqlStatement = "UPDATE Table1 " +

"SET Employees = @Employees, Position = @Position, Team = @Team " +

"WHERE Id = @Id";

try

{

connection.Open();

SqlCommand cmd = new SqlCommand(sqlStatement, connection);

cmd.Parameters.AddWithValue("@Employees", employee);

cmd.Parameters.AddWithValue("@Position", position);

cmd.Parameters.AddWithValue("@Team", team);

cmd.Parameters.AddWithValue("@Id", id);

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

}

catch (System.Data.SqlClient.SqlException ex)

{

string msg = "Insert/Update Error:";

msg += ex.Message;

throw new Exception(msg);

}

finally

{

connection.Close();

}

}

As you can see, the code above was pretty self explanatory and very straight forward. Now let’s set up the events for handling the Edit and Update exections.

Editing and Updating the Data in GridView

One of the good things about GridView is that it provides a built-in CommandField Buttons which allows us to perform certain actions like editing, updating,deleting and selecting of GridView data.

To add those command fields mentioned in the GridView you can follow these few steps below:

1. Switch to Design View
2. Right Click on the GridView and Select  --> Show Smart Tag --> Add New Columns
3. On the List Select CommandField
4. Check Delete and Edit/Update options then OK

As you can see the Edit and Delete CommandField are automatically added in the last column of GridView.  Now we can start to write our codes for editing and updating the information in the GridView.

In-order to perform Edit and Update in GridView we need to use three events ( GridView_RowEditing, GridView_RowCancelingEdit , GridView_RowUpdating). For those who do not know on how to generate Events in GridView you can follow these steps below:

1. Switch to Design View in Visual Studio Designer
2. Click on the GridView
3. Navigate to the GridView Property Pane and then SWITCH to Event Properties
4. From there you would be able to find the list of events including those three  events mentioned above
5. Double Click on that to generate the Event handler for you
6. Then write the codes there

Here are the codes for each event:

protected void GridViewEmployee_RowEditing(object sender, GridViewEditEventArgs e)

{

GridViewEmployee.EditIndex = e.NewEditIndex; // turn to edit mode

BindGridView(); // Rebind GridView to show the data in edit mode

}

protected void GridViewEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

GridViewEmployee.EditIndex = -1; //swicth back to default mode

BindGridView(); // Rebind GridView to show the data in default mode

}

protected void GridViewEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

//Accessing Edited values from the GridView

string id = ((Label)GridViewEmployee.Rows[e.RowIndex].Cells[3].FindControl("LabelID")).Text; //ID

string employee = ((TextBox)GridViewEmployee.Rows[e.RowIndex].Cells[0].FindControl("TextBoxEditEmployee")).Text; //Employee

string position = ((TextBox)GridViewEmployee.Rows[e.RowIndex].Cells[1].FindControl("TextBoxEditPosition")).Text; //Position

string team = ((TextBox)GridViewEmployee.Rows[e.RowIndex].Cells[2].FindControl("TextBoxEditTeam")).Text; //Team

UpdateRecord(id, employee, position, team); // call update method

GridViewEmployee.EditIndex = -1; //Turn the Grid to read only mode

BindGridView(); // Rebind GridView to reflect changes made

Response.Write("Update Seccessful!");

}

When you run the page, the output would look similar to this:

GridView in Read-Only Mode

GridView in Edit Mode

GridView after Edit Mode

Since, you already know how to edit the data in the GridView, then let’s go ahead and implement the Deletion.

Performing Delete in GridView

Here’s the method for the Deletion

private void DeleteRecord(string ID)

{

SqlConnection connection = new SqlConnection(GetConnectionString());

string sqlStatement = "DELETE FROM Table1 WHERE Id = @Id";

try

{

connection.Open();

SqlCommand cmd = new SqlCommand(sqlStatement, connection);

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

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

}

catch (System.Data.SqlClient.SqlException ex)

{

string msg = "Deletion Error:";

msg += ex.Message;

throw new Exception(msg);

}

finally

{

connection.Close();

}

}

Since we are using the Built-in Delete CommandField Button in GridView, then we can use the GridView_RowDeleting event to delete specific row in GridView.

Here’s the code block below:

protected void GridViewEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

//get the ID of the selected row

string id = ((Label)GridViewEmployee.Rows[e.RowIndex].Cells[3].FindControl("LabelID")).Text;

DeleteRecord(id); //call the method for delete

BindGridView(); // Rebind GridView to reflect changes made

}

That’s it! Hope you will find this example useful!

To rate this article please register or login

Author

Vinz Vinz (Member since:4/15/2009)
Working as a SDE at NCR Corporation and specializing on ASP.NET technologies. I am an active forum member and a regular contributor at the official ASP.NET forum site and one of the Top Community member with All- Star recognition level.I voluntarily spent my extra time helping other geeks through forums, blogs and articles. I have been awarded as Microsoft MVP - ASP/ASP.NET for 2009.

Comments (7)

  • 6/16/2009 1:42:28 AM by: 
    thax for this code but not updating . please help me
  • Vinz 6/18/2009 6:56:01 PM by:  Vinz
    Hi, what exactly do you mean by "not updating?".. Did you get any error or something?
  • 9/29/2009 7:22:57 AM by: 
    Hi, Thanks for the code. I tried running the code but it does not show the data on gridview binding. Actually I want to get this gridview filled on the basis of selection made on another gridview and perform add, edit and update things. I am facing problem with - "Text='<%# Bind("Team") %>'/", dont know what to put here. Can you please help me with this. Thanks in advance. -Manik
  • maniksangal 9/29/2009 7:24:45 AM by:  maniksangal
    Hi, Thanks for the code. I tried running the code but it does not show the data on gridview binding. Actually I want to get this gridview filled on the basis of selection made on another gridview and perform add, edit and update things. I am facing problem with - "Text='<%# Bind("Team") %>'/", dont know what to put here. Can you please help me with this. Thanks in advance. -Manik
  • maniksangal 9/29/2009 7:25:17 AM by:  maniksangal
    Hi, Thanks for the code. I tried running the code but it does not show the data on gridview binding. Actually I want to get this gridview filled on the basis of selection made on another gridview and perform add, edit and update things. I am facing problem with - "Text='<%# Bind("Team") %>'/", dont know what to put here. Can you please help me with this. Thanks in advance. -Manik
  • maniksangal 9/29/2009 8:46:48 AM by:  maniksangal
    Hi, Thanks for the code. I tried running the code but it does not show the data on gridview binding. Actually I want to get this gridview filled on the basis of selection made on another gridview and perform add, edit and update things. I am facing problem with - "Text='<%# Bind("Team") %>'/", dont know what to put here. Can you please help me with this. Thanks in advance. -Manik
  • Vinz 9/29/2009 9:28:13 PM by:  Vinz
    what's the error you are getting?

Post a comment

Comment (No HTML)  

Type the characters:
 *
 
   

Related articles

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest Articles

  • Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know about bugs and/or errors & give suggestions to improve this ListBox control.
  • I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on various browsers and it works fine.
  • As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind there is question arise what is PagedDataSource. PagedDataSource is a class which encapsulates
  • So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.
  • So this is the approach that I've adopted to solve the Hover Delay problem. Although originally I developed Hover Delay to deactivate the click event for 1 second on a GridView row, later I also used Hover Delay to deactivate Drag n Drop of GridView rows. Kindly let me know if any one has some other better or different solution.
  • In this article I will explain how to import data from EXCEL to SQL in ASP.NET . In many situations we have data in the form of excel sheet but we have the requirement to have that data in SQL SERVER DB. I have explained importing data both from Excel 97-2003 as well as Excel 2007 format.
  • The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.
  • That’s all about this technique. Just download the sample application and happy CSS! I have tested this application on various browsers and it worked fine.
  • This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].
  • This Article is used to insert a numeric value on the sever control(text box) This is a java script code for the the client side validation. On Page Load Event You can change the events in txtNoOfQuestion.Attributes.Add("onkeypress", "return numericOnly(this);"); like onfocus events like other according to needs.
  • I have toggled visibility of all TD elements of a GridView column in order to create an illusion of smooth dynamic effect with the help of setTimeout method through recursion. Different browsers have different effects of Expanding / Collapsing GridView Columns. In Internet Explorer 7/8, Safari, Google Chrome and Opera, it seems that columns are Exp
  • In this article, I've used the setTimeout method in order to achieve a smooth expand/collapse functionality.
  • Introduction I am going to present here a functionality that selects / deselects all checkboxes of a particular column inside a GridView control, provided the header checkbox of that column is checked or unchecked using JavaScript. This functionality also has a feature that when all checkboxes of a particular column inside the GridView are check
  • This article describes how to toggle the states of all CheckBoxes inside a particular DataGridView column.
  • This article describes how to apply client-side mouse over & mouse out effects on the GridView’s rows.