home » articles » Adding Rows in GridView with Edit, Update and Delete Functionality
Published on 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">
<asp:TextBox ID="TextBoxEditPosition" runat="server" Text='<%# Bind("Position") %>'/>
<asp:Label ID="LabelPosition" runat="server" Text='<%# Bind("Position") %>'/>
<asp:TextBox ID="TextBoxPosition" runat="server"/>
</asp:TemplateField>
<asp:TemplateField HeaderText="Team Name">
<asp:TextBox ID="TextBoxEditTeam" runat="server" Text='<%# Bind("Team") %>'/>
<asp:Label ID="LabelTeam" runat="server" Text='<%# Bind("Team") %>'/>
<asp:TextBox ID="TextBoxTeam" runat="server"/>
<asp:TemplateField HeaderText="Employee ID">
<asp:Label ID="LabelID" runat="server" Text='<%# Bind("Id") %>'/>
<asp:Button ID="Button1" runat="server" Text="Add New" OnClick="Button1_Click" />
<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 View2. Right Click on the GridView and Select --> Show Smart Tag --> Add New Columns3. On the List Select CommandField4. Check Delete and Edit/Update options then OKAs 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 Designer2. Click on the GridView3. Navigate to the GridView Property Pane and then SWITCH to Event Properties4. From there you would be able to find the list of events including those three events mentioned above5. Double Click on that to generate the Event handler for you6. Then write the codes thereHere 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)
string sqlStatement = "DELETE FROM Table1 WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", ID);
string msg = "Deletion Error:";
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.
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
That’s it! Hope you will find this example useful!
Comment (No HTML)
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:
More Articles