In this article, we will learn how to use the RowUpdating event of GridView in Asp.Net using C# with an example.

This example takes advantage of GridView control and perform edit and update operations on data and save the changed data in the database.

RowUpdating event in the GridView in Asp.Net using C#

Let’s get started by adding a GridView control to our ASPX web page.

HTML

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnRowEditing="OnRowEditing" CssClass="gv">
    <Columns>
        <asp:BoundField DataField="CustomerName" HeaderText="Customer Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="CustomerEmail" HeaderText="Customer Email" ItemStyle-Width="150" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
                <asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

CSS

<style>
    .gv {
        border: solid 2px black;
    }

    .header {
        background-color: #646464;
        font-family: Arial;
        color: White;
        border: none 0px transparent;
        height: 25px;
        text-align: center;
        font-size: 16px;
    }

    .rows {
        background-color: #fff;
        font-family: Arial;
        font-size: 14px;
        color: #000;
        min-height: 25px;
        text-align: left;
        border: none 0px transparent;
    }

    .selectedrow {
        background-color: #ff8000;
        font-family: Arial;
        color: #fff;
        font-weight: bold;
        text-align: left;
    }

    .pager {
        background-color: #646464;
        font-family: Arial;
        color: White;
        height: 30px;
        text-align: left;
    }

    .gv td {
        padding: 5px;
    }

    .gv th {
        padding: 5px;
    }
</style>

You need to import the following namespace

using System.Data;
using System.Data.SqlClient;

Populating the GridView with data from the Database

Create a database table by running the script below:

SET ansi_nulls ON 
go 
SET quoted_identifier ON 
go 
CREATE TABLE [dbo].[customers] 
  ( 
     [customerid]    [INT] IDENTITY(1, 1) NOT NULL, 
     [customername]  [NVARCHAR](50) NULL, 
     [customeremail] [NVARCHAR](50) NULL 
  ) 
ON [PRIMARY] 

go

At the page load, load the data into a session variable, then bind the GridView with the data in that variable.

LoadCustomersDataTable function

    void LoadCustomersDataTable()
    {
        DataTable dt = new DataTable();
        string conn_str = "Data Source=ServerName;Initial Catalog=customersdb;Integrated Security=True";
        using (SqlConnection con = new SqlConnection(conn_str))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT * FROM Customers";
                cmd.Connection = con;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(dt);
                    gvCustomers.DataSource = dt;
                    gvCustomers.DataBind();
                }
            }
        }
        ViewState["dt"] = dt;
        this.BindCustomers();

    }

BindCustomers function

    private void BindCustomers()
    {
        gvCustomers.DataSource = ViewState["dt"] as DataTable;
        gvCustomers.DataBind();

    }

Page_Load function

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            LoadCustomersDataTable();
            BindCustomers();
        }
    }

When the user clicks on the Edit button inside the row, the OnRowEdit event handler is called.

OnRowEditing function

    protected void OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        gvCustomers.EditIndex = e.NewEditIndex;
        BindCustomers();
    }

The event handlers for update data are given as follows.

OnUpdate function

    protected void OnUpdate(object sender, EventArgs e)
    {
        GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
        string customerName = (row.Cells[0].Controls[0] as TextBox).Text;
        string customerEmail = (row.Cells[1].Controls[0] as TextBox).Text;
        DataTable dt = ViewState["dt"] as DataTable;
        dt.Rows[row.RowIndex]["CustomerName"] = customerName;
        dt.Rows[row.RowIndex]["CustomerEmail"] = customerEmail;
        ViewState["dt"] = dt;
        gvCustomers.EditIndex = -1;
        this.BindCustomers();
    }

Inside the cancel event handler, the GridView EditIndex is set to negative 1 and the GridView is populated with the temporary data saved in ViewState.

OnCancel function

    protected void OnCancel(object sender, EventArgs e)
    {
        gvCustomers.EditIndex = -1;
        BindCustomers();
    }

Run the application, make changes to existing data and watch the DataTable dt getting the new changes saved in it.

Related Articles

Last modified: October 4, 2019

Comments

Write a Reply or Comment

Your email address will not be published.