Thursday, 3 July 2014

OnClick event upon selecting Row on the GridView

This post says about how to select a row upon clicking GridView and accessing its cell values

Firstly add the GridView into the page from tool box.

Check the .aspx code and update if necessary to

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BorderStyle="Double" OnRowDataBound = "OnRowDataBound" OnSelectedIndexChanged = "GridView1_OnSelectedIndexChanged"> </asp:GridView>

For binding the data to gridview while the page gets loaded, follow the below link
DataBinding to GridView

Add the following functions into the .aspx.cs file

protected void GridView1_OnSelectedIndexChanged(object sender, EventArgs e)

        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowIndex == GridView1.SelectedIndex)
                {
                    row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
                    row.ToolTip = string.Empty;
                }
                else
                {
                    row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
                }
            }
        }


protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (Page.IsPostBack)
            {

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
                    //e.Row.ToolTip = "Click to select this row.";
                }
            }
        }



For accessing the selected row data you can access it the following way

GridView1.SelectedRow.Cells[3].Text


No comments:

Post a Comment