GridView Events For Beginners

The GridView control is a tabular databound control but sometimes it is used  like a speardsheet control. It came with ASP.NET 2.0 and is an improved version of the DataGrid control. It displays a set of data items in an HTML table. We can use this to display data from a database and edit, sort and select the data.

Design a GridView

<asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="False"
    DataKeyNames="Emp_id" onrowcancelingedit="EmployeeGridView_RowCancelingEdit"
     onrowediting="EmployeeGridView_RowEditing"             onrowdeleting="EmployeeGridView_RowDeleting"
            onrowupdating="EmployeeGridView_RowUpdating">  
    <Columns>
    <asp:TemplateField HeaderText="Sr.No">
    <ItemTemplate>    <%#Container.DataItemIndex+1 %>    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>    <%#Eval("Emp_name") %>    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Emp_name") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>   
     <asp:TemplateField HeaderText="Experience">
    <ItemTemplate>    <%#Eval("Emp_exp") %>    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtempexp" runat="server" Text='<%#Eval("Emp_exp") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>
     <asp:TemplateField HeaderText="Address">
    <ItemTemplate>    <%#Eval("Emp_address") %>    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtempaddress" runat="server" Text='<%#Eval("Emp_address") %>'></asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateField>
  <asp:CommandField ShowEditButton="true" ButtonType ="Image" EditImageUrl="image/edit.jpg" UpdateImageUrl="image/accept.jpg"
CancelImageUrl="image/error.jpg" HeaderText="Edit" />
  <asp:CommandField ShowDeleteButton="true" ButtonType="Image" DeleteImageUrl="image/error.jpg" HeaderText="Delete" /> 
    </Columns>
    </asp:GridView
>


AutoGenerateColumns: This property accepts only a Boolean value. The default value is true. When we set it to False that means the BoundField objects are  not created automatically; we will create the fields manually.

DataKeyNames: This property is used to associate a value with each row in the GridView. Here we can assign the name of a single database column or more than one column. When we assign more than one database columns then they are specified separated by commas. It represents datakey values. By this we uniquely identifiy records in GridView rows.

<Columns>: It is a collection of columns that the GridView contains. By this we can control what GridView columns are displayed, which means we can change the order of the appearance of the columns.

<asp:TemplateField>: Is used to add ASP.Net controls in GridView rows. One TemplateField represents one column in the GridView. It customizes the appearance of the UI in the GridView. It is useful when we are using a GridView to edit a database record.

<ItemTemplate>: It specifies the contents that are displayed in a TemplateField object. It displays a layout for the TemplateField.

<EditItemTemplate>: It also specifies contents that are displayed in a TemplateField but in EditMode.

Eval: It is a method that is used to display data. In this method we pass a database field name as an argument and that database field is displayed by this.

<asp:CommandField>: It is a special field that displays command buttons to perform selecting, editing, inserting and deleting.

Create a table in the database that contains some data. That table is tbl_employee and its definition is as follows.



Create a connection string for the database; here the SQL server database connection string is:

//connection string for database connection
string connstr = @"Data Source=SANPEEP-PC\SANDEEP;Initial Catalog=Employee;Persist Security Info=True;User ID=sa;Password=123;Pooling=False";

A verbatim string literal begins with an @, which is followed by a quoted string. The contents of the quoted string are accepted without modification and can span two or more lines. Thus, you can include newlines, tabs, and so on, but you don't need to use escape sequences.

Here I am working with a connected mode and using the SqlCommand class; that description is available at:

http://www.c-sharpcorner.com/UploadFile/00c99e/8028/

Display Data in GridView:

Create a stored procedure to get all the data from the database:

CREATE PROCEDURE dbo.GetEmployeeInfo                 
AS
            select Emp_id,Emp_name,Emp_exp,Emp_address from tbl_employee


Create a method that displays data in a GridView using the above stored procedure:

public void FillGrid()
{
    SqlConnection con=new SqlConnection(connstr);
    con.Open();
    SqlCommand cmd = new SqlCommand("GetEmployeeInfo", con);
    SqlDataReader dr = cmd.ExecuteReader();//it reads froword only data from database
    DataTable dt = new DataTable();//object of data table that uses to conatin whole data
    dt.Load(dr);//Sql Data reader data load in data table it is DataTable Method.
    EmployeeGridView.DataSource = dt;
    EmployeeGridView.DataBind();
}

And call this method from the appropriate location in the class where you want. I call this method in the Page Load of the web form:

protected void Page_Load(object sender, EventArgs e)
{
    //only call when page first time load
    if (!Page.IsPostBack)
    {
        FillGrid();//method call
    }
}

Edit Data in GridView

Create a stored procedure to update a row in the database:

CREATE PROCEDURE dbo.EmployeeUpdate
            (
            @emp_id int,@emp_name varchar(30),
            @emp_exp varchar(10),@emp_address varchar(300)
            )          
AS
update
tbl_employee set Emp_name=@emp_name,Emp_exp=@emp_exp,Emp_address=@emp_address where Emp_id=@emp_id

For editing data in a GridView we use three events.

RowCancelingEdit: This event is raised when we cancel the update of a record, which means we use this when we are in editmode of a GridView and we want to get the GridView back to view mode without any update.

protected void EmployeeGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    EmployeeGridView.EditIndex = -1;
    FillGrid();
//Fill GridView again call method
}

The EditIndex property of a GridView determines the index of a row in edit mode. EditIndex=-1 means that no row is in edit mode.

RowEditing: This GridView event is used to change the GridView mode. This event is raised when a row's edit button is clicked but before the GridView enters into Edit Mode.

protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
    EmployeeGridView.EditIndex = e.NewEditIndex;
    FillGrid();
//Fill GridView again call method
}

Here e.NewEditIndex determines which row is clicked and that will be in edit mode.

OUTPUT



RowUpdating: Is raised before a GridView updates a record, which means that the row's update button has been clicked but before the GridView updates the row.

    {
        int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
        string name = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempname")).Text;//get TextBox Value in EditItemTemplet that row is clicked
        string experience = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempexp")).Text;
        string address = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempaddress")).Text;
        SqlConnection con = new SqlConnection(connstr);
        con.Open();
        SqlCommand cmd = new SqlCommand("EmployeeUpdate",con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@emp_id ", empid);
        cmd.Parameters.AddWithValue("@emp_name ", name);
        cmd.Parameters.AddWithValue("@emp_exp ", experience);
        cmd.Parameters.AddWithValue("@emp_address ", address);
        cmd.ExecuteNonQuery();//Sql Command Class method return effected rows use for insert,update, delete
        EmployeeGridView.EditIndex = -1;// no row in edit mode
        FillGrid();
//call method for agin fill grid after update
    }

Here we get a unqiue id for the update and pass parameters to the StoredProcedure for database update.

Delete Row in GridView

Here we use the GridView RowDeleting Event. This event is raised when the row's delete button is clicked but before the row is deleted.

Create a stored procedure for deleting a row in the database on a particular id base.

CREATE PROCEDURE dbo.DeleteEmployee
            (
            @emp_id int
            )          
AS
            Delete  from tbl_employee where Emp_id=@emp_id


Create a RowDeleting Event

protected void EmployeeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int empid=Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());
    SqlConnection con=new SqlConnection(connstr);
    con.Open();
    SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@emp_id ", empid);
    cmd.ExecuteNonQuery();
    FillGrid();
}


Similar Articles