Asp.Net : How to add click event to rows in GridView and highlight the row selected

In this tutorial I am going to explain to how to attach a click event to rows in gridView.  By design gridView don’t have property to add a row click event in gridview. We need to have a custom implementation to attach a row click event in gridview at runtime.

Attaching the Click event to each Rows

We need to loop through each rows in gridvew and use the above code to attach the click event. You can use the GridView_RowCreated event to add row click event like given below

protected void GridView8_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Attach click event to each row in Gridview
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView8, "Select$" + e.Row.RowIndex);
            }
        }

Highlighting rows in GridView

You can use the below code to hightlight row in gridview on click event. code snippet also contains the logic to handle previously selected row and clearing out the color from previously selected row.

  protected void GridView8_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //Check if Viewstate is null or not
            if (ViewState["PreviousRowIndex"] != null)
            {
                //Get the Previously selected rowindex
                var previousRowIndex = (int)ViewState["PreviousRowIndex"];
                //Get the previously selected row
                GridViewRow PreviousRow = GridView8.Rows[previousRowIndex];
                //Assign back color to previously selected row
                PreviousRow.BackColor = System.Drawing.Color.White;
            }
            //Get the Command Name
            // string currentCommand = e.CommandName;
            //Get the Selected RowIndex
            int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
            //Get the GridViewRow from Current Row Index
            GridViewRow row = GridView8.Rows[currentRowIndex];
            //Assign the Back Color to Yellow
            //Change this color as per your need
            row.BackColor = System.Drawing.Color.Blue;
            //Assign the index as PreviousRowIndex
            ViewState["PreviousRowIndex"] = currentRowIndex;
        } 

However since you attaching the click event to gridview, when you click on the row you will face the Invalid Postback issue. To resolve this you need set the EnableEventValidation property of page to false.

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="YourPage.aspx.cs" Inherits="WebApplicationcSharp.Grid" %> 

Complete Code is given below

<asp:GridView ID="GridView8" CellPadding="5" runat="server" ShowFooter="True" AutoGenerateColumns="false"
 OnRowCreated="GridView8_RowCreated" OnRowCommand="GridView8_RowCommand">
 <Columns>
 <!-- You can add other columns here -->
 <asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Width="150" SortExpression="Price" />
 <asp:BoundField DataField="Items" HeaderText="Items" ItemStyle-Width="150" SortExpression="Price" />
 </Columns>
 </asp:GridView>
 

C#:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridView8.DataSource = this.Get_TotalDetails();
                GridView8.DataBind();
            }
        }
        //Populate some dummy data for GridView
        public DataTable Get_TotalDetails()
        {
            DataTable dt = new DataTable();
            DataRow dr;
            string Price = "70,28,70,52,40";
            string Items = "Item1,Item2,Item3,Item4,Item5";
            string[] list4 = Price.Split(',');
            string[] list1 = Items.Split(',');
            dt.Columns.Add("Price", typeof(int));
            dt.Columns.Add("Items", typeof(String));
            for (int i = 0; i < list4.Length; i++)
            {
                dr = dt.NewRow();
                dr["Price"] = list4[i];
                dr["Items"] = list1[i];
                dt.Rows.Add(dr);
            }
            return dt;
        }

        protected void GridView8_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Attach click event to each row in Gridview
                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView8, "Select$" + e.Row.RowIndex);
            }
        }
        protected void GridView8_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //Check if Viewstate is null or not
            if (ViewState["PreviousRowIndex"] != null)
            {
                //Get the Previously selected rowindex
                var previousRowIndex = (int)ViewState["PreviousRowIndex"];
                //Get the previously selected row
                GridViewRow PreviousRow = GridView8.Rows[previousRowIndex];
                //Assign back color to previously selected row
                PreviousRow.BackColor = System.Drawing.Color.White;
            }
             //Get the Selected RowIndex
            int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
            //Get the GridViewRow from Current Row Index
            GridViewRow row = GridView8.Rows[currentRowIndex];
            //Assign the Back Color to Blue
            //Change this color as per your need
            row.BackColor = System.Drawing.Color.Blue;
            //Assign the index as PreviousRowIndex
            ViewState["PreviousRowIndex"] = currentRowIndex;
        }
 

You can find a working demo here

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: