There are 119 guests and 0 members online. Who is online?

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

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">

<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)

  • Vinz 9/29/2009 9:28:13 PM by:  Vinz
    what's the error you are getting?
  • 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
  • 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 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
  • 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
  • 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?
  • 6/16/2009 1:42:28 AM by: 
    thax for this code but not updating . please help me

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

.
  • how to change Visual Studio's default browser
    12/15/2009
    how to change Visual Studio's default browser
  • Access dropdownlist inside the gridview
    12/10/2009
    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.
  • JavaScript Expandable / Collapsible Panel Control
    12/4/2009
    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.
  • JavaScript ListBox Control
    12/3/2009
    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 ab...
  • Multiple File Upload User Control
    11/27/2009
    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.
  • Slide-Show User Control
    11/26/2009
    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 variou...
  • Implement: Paging in Repeater or Datalist Control
    11/18/2009
    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 t...
  • JavaScript Context Menu Control
    11/6/2009
    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.
  • Maintaining States of Selected CheckBoxes in Different Pages inside the GridView
    11/4/2009
    So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • GridView Rows Navigation Using Arrow (Up/Down) Keys
    11/4/2009
    I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.

More Articles