ASP.NET GridView is a powerful control for displaying and manipulating tabular data in web applications. However, understanding how to handle its various events can be daunting for beginners. In this guide, we'll explore each GridView event in simple terms, accompanied by practical examples using the "Employee" table.
GridView Source:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnDataBound="GridView1_DataBound"
OnRowCommand="GridView1_RowCommand"
OnRowCreated="GridView1_RowCreated"
OnRowDataBound="GridView1_RowDataBound"
OnRowDeleted="GridView1_RowDeleted"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdated="GridView1_RowUpdated"
OnRowUpdating="GridView1_RowUpdating"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting"
OnSorted="GridView1_Sorted"
AllowPaging="True" DataKeyNames="Id" AllowSorting="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
Code Behind:
string connectionString = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
if (!IsPostBack)
{
{
BindGridView();
}
}
}
private string SortDirection
{
get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
set { ViewState["SortDirection"] = value; }
}
private void BindGridView(string sortExpression = null)
{
string query = "SELECT * FROM Employee";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataTable table = new DataTable();
adapter.Fill(table);
if (sortExpression != null)
{
DataView dv = table.AsDataView();
this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
dv.Sort = sortExpression + " " + this.SortDirection;
GridView1.DataSource = dv;
}
else
{
GridView1.DataSource = table;
}
GridView1.DataBind();
}
}
}
- DataBound Event:
Occurs after the GridView is bound to a data source. This event is handy for performing tasks after data binding, such as displaying messages or modifying the GridView's appearance.
protected void GridView1_DataBound(object sender, EventArgs e)
{
// Example: Display a message after data binding
lblMessage.Text = "GridView data bound successfully!";
}
- RowCreated Event:
Occurs when a GridView row is created. You can use this event to tweak row attributes or attach client-side scripts. For instance, changing row colors on hover.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
// Example: Modify row attributes during row creation
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='lightgray';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
}
}
- RowDataBound Event:
Occurs when a GridView row is bound to data. Use this event to customize row data dynamically. For example, highlighting rows based on certain conditions like age > 40.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the age value from the data source
DataRowView rowView = e.Row.DataItem as DataRowView;
if (rowView != null)
{
int age = Convert.ToInt32(rowView["Age"]);
if (age > 40)
{
e.Row.Cells[2].ForeColor = System.Drawing.Color.Red;
}
}
}
}
- RowEditing Event:
Occurs when a row's Edit button is clicked. Handle this event to enable row editing functionality.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
- RowCancelingEdit Event:
Occurs when a row's Cancel button is clicked during editing mode. Use this event to cancel row editing and revert changes.
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
- RowUpdating Event:
Occurs when a row's Update button is clicked. Handle this event to update the database with edited row data.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name = ((TextBox)row.Cells[0].Controls[0]).Text;
string email = ((TextBox)row.Cells[1].Controls[0]).Text;
int age = int.Parse(((TextBox)row.Cells[2].Controls[0]).Text);
string country = ((TextBox)row.Cells[3].Controls[0]).Text;
// Update the database
using (YourDbContext context = new YourDbContext())
{
var employee = context.Employees.Find(id);
if (employee != null)
{
employee.Name = name;
employee.Email = email;
employee.Age = age;
employee.Country = country;
context.SaveChanges();
}
}
GridView1.EditIndex = -1;
BindGridView();
}
- RowUpdated Event:
Occurs after a row has been successfully updated in the database. You can perform post-update actions here, like displaying a success message.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
lblMessage.Text = "GridView row updated successfully!";
}
- RowDeleting Event:
Occurs when a row's Delete button is clicked. Handle this event to delete the row from the database.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
// Delete the record from the database
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
connection.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM Employee WHERE Id=@Id", connection);
cmd.Parameters.AddWithValue("@Id", id);
cmd.ExecuteNonQuery();
}
BindGridView();
}
- RowDeleted Event:
Occurs after a row has been successfully deleted from the database. You can handle exceptions and display error messages if deletion fails.
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception == null)
{
// Row deleted successfully
lblMessage.Text = "Row deleted successfully!";
}
else
{
// Handle exception if row deletion fails
lblMessage.Text = "Error deleting row: " + e.Exception.Message;
}
}
- SelectedIndexChanged Event:
Occurs when the selected index has changed. You can use this event to perform actions based on the selected row, like displaying its data.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the selected row and display its data
GridViewRow selectedRow = GridView1.SelectedRow;
if (selectedRow != null)
{
lblMessage.Text = "Selected Employee: " + selectedRow.Cells[0].Text + ", " + selectedRow.Cells[1].Text;
}
}
- PageIndexChanging Event:
Occurs when the page index is changing. Handle this event to implement paging functionality for the GridView.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
- RowCommand Event:
Occurs when a button is clicked in a GridView row. You can handle different button clicks and perform corresponding actions.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
// Delete the row from the database
// Your deletion logic here
lblMessage.Text = "Row deleted successfully!";
BindGridView(); // Refresh GridView after deletion
}
}
- Sorting and Sorted Events:
Sorting event occurs when the sorting operation is performed, and Sorted event occurs after the sorting operation is complete. Handle these events to implement sorting functionality for the GridView.
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
this.BindGridView(e.SortExpression);
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
lblMessage.Text = "GridView sorted successfully!";
}
Complete Code:
string connectionString = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
if (!IsPostBack)
{
{
BindGridView();
}
}
}
private string SortDirection
{
get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
set { ViewState["SortDirection"] = value; }
}
private void BindGridView(string sortExpression = null)
{
string query = "SELECT * FROM Employee";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataTable table = new DataTable();
adapter.Fill(table);
if (sortExpression != null)
{
DataView dv = table.AsDataView();
this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
dv.Sort = sortExpression + " " + this.SortDirection;
GridView1.DataSource = dv;
}
else
{
GridView1.DataSource = table;
}
GridView1.DataBind();
}
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
// Example: Display a message after data binding
lblMessage.Text = "GridView data bound successfully!";
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
// Example: Modify row attributes during row creation
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='lightgray';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the age value from the data source
DataRowView rowView = e.Row.DataItem as DataRowView;
if (rowView != null)
{
int age = Convert.ToInt32(rowView["Age"]);
if (age > 40)
{
e.Row.Cells[2].ForeColor = System.Drawing.Color.Red;
}
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = ((TextBox)row.Cells[0].Controls[0]).Text;
string email = ((TextBox)row.Cells[1].Controls[0]).Text;
int age = Convert.ToInt32(((TextBox)row.Cells[2].Controls[0]).Text);
string country = ((TextBox)row.Cells[3].Controls[0]).Text;
// Update the record in the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("UPDATE Employee SET Name=@Name, Email=@Email, Age=@Age, Country=@Country WHERE Id=@Id", connection);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Email", email);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Parameters.AddWithValue("@Id", id);
cmd.ExecuteNonQuery();
}
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
lblMessage.Text = "GridView row updated successfully!";
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
// Delete the record from the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM Employee WHERE Id=@Id", connection);
cmd.Parameters.AddWithValue("@Id", id);
cmd.ExecuteNonQuery();
}
BindGridView();
}
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception == null)
{
// Row deleted successfully
lblMessage.Text = "Row deleted successfully!";
}
else
{
// Handle exception if row deletion fails
lblMessage.Text = "Error deleting row: " + e.Exception.Message;
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectedRow = GridView1.SelectedRow;
if (selectedRow != null)
{
lblMessage.Text = "Selected Employee: " + selectedRow.Cells[0].Text + ", " + selectedRow.Cells[1].Text;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
// Delete the row from the database
// Your deletion logic here
lblMessage.Text = "Row deleted successfully!";
BindGridView(); // Refresh GridView after deletion
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
this.BindGridView(e.SortExpression);
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
// Perform any post-sorting actions here
lblMessage.Text = "GridView sorted successfully!";
}
}