Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 123, comments - 361, trackbacks - 0

My Links

News

Archives

Image Galleries

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

    }

 

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

Print | posted on Wednesday, June 10, 2009 2:28 AM |

Feedback

Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

This is an excellant artical to have add, edit and delete functions in a grid view. It worked for me and helped saving lot of time.

Thanks dude!!!
6/19/2009 10:50 AM | Srini
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

wrong it is not updatiing any value..
Its caputuring old values
6/22/2009 8:18 AM | vikas
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

Hi Vikas,

Have you tried implementing it? I have tested this example before posting it here so I'm sure the update works...
6/22/2009 8:10 PM | Vinz
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

Thanks. Its working fine for me. Thank u again

Regards
Anowar
6/23/2009 9:33 AM | Anowar
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

@Vikas

Were you able to make it work now? If you are binding your GridView at Page_Load event then be sure to wrap it within Not IsPostback block so that you will be able to get the updated values..
7/20/2009 1:04 PM | Vinz
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

Very Thanks... Have a nice day~~~
7/28/2009 1:43 PM | devker
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

Hi,
This is really good artical.It help a lot to understand basics of GridView.

Thanks
Akshay Kr Saxena
7/29/2009 7:06 PM | Akshay
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

THANK YOU!! I couldn't find any good help working with GridViews until I came across your site. You are AWESOME! Thank you. =)
8/12/2009 5:17 PM | Charity
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

This is one of the better example on-line for the Edit/update problems people seem to have with gridview
8/25/2009 2:38 PM | Very Good
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

Can you show me what you coded in your Page Load ?

I am having problem with the Page Load and if I don't have Postback, I am not able to update the database using the new values I entered.

Thanks.
10/5/2009 10:10 PM | Dave
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

@Dave,
You can check the previous article about Adding Rows in GridView. Check this link:
http://geekswithblogs.net/dotNETvinz/archive/2009/06/09/adding-rows-in-gridview.aspx
10/5/2009 10:42 PM | Vinz
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

not sure if you experience this scenario ...

when i click update, the newly updated value not being captured.

let's say, my original value is : 1
when i click update, the field will be 1,,
then i click edit and update again, it will be, 1,,1,,

it seems the old value being concat again.
10/6/2009 7:05 PM | Dave
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

@Dave,

Check your database if it saves the correct values there..
10/6/2009 7:37 PM | Vinz
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

It can't get into database at all because, it is numeric field and 1,, is string.

I don't think anything wrong with my code, it is pretty standard like what you use here. I just don't understand even if I put empty value and click update, I will get ,, as the value.
---------------

protected void gvList_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtOverrideMin = (TextBox)gvList.Rows[e.RowIndex].FindControl("txtOverrideMin");
TextBox txtOverrideMax = (TextBox)gvList.Rows[e.RowIndex].FindControl("txtOverrideMax");
TextBox txtComments = (TextBox)gvList.Rows[e.RowIndex].FindControl("txtComments");

Int32.TryParse(txtOverride.Text, out Qty_override);
Int32.TryParse(txtOverrideMin.Text, out Qty_override_min);
Int32.TryParse(txtOverrideMax.Text, out Qty_override_max);

comments = txtComments.Text;

10/6/2009 9:09 PM | Dave
Gravatar

# re: Adding Rows in GridView with Edit, Update and Delete Functionality

Hay this is good article . I have one more qry . in the grid if i have a dropdown how should i edit the value of that ?
10/29/2009 5:32 PM | Manjunath
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: