Thursday, January 19, 2012

Adding Rows in GridView with Edit, Update and Delete Functionality

This example is a continuation of my previous post about “Adding Rows in GridView”. In this example I 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 proceed.
To get started, 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"
onrowdeleting="GridViewEmployee_RowDeleting">
<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" ShowDeleteButton />
</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, Cancelling 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, we 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
}

0 comments:

Post a Comment