Selecting GridView Row by clicking anywhere on the Row in Asp.Net - C#

In this blog I am going to how to show how to select GridView Row when mouse is clicked anywhere on the GridView Row in ASP.Net- C#

  •  First of all add a page to your solution and add a gridview, a link button which will be used to render ASP.Net _doPostBack JavaScript as it requires for RowSelection.
<head runat="server">
    <title></title>
<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 10pt;
    }
    td
    {
        cursor: pointer;
    }
    .hover_row
    {
        background-color: #A1DCF2;
    }
</style>
 <script type="text/javascript">
     $(function () {
         $("[id*=gvDetails] td").hover(function () {
             $("td", $(this).closest("tr")).addClass("hover_row");
         }, function () {
             $("td", $(this).closest("tr")).removeClass("hover_row");
         });
     });
</script>
</head>

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvDetails" HeaderStyle-BackColor="AliceBlue" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" HeaderStyle-ForeColor="Black" runat="server"
            onselectedindexchanged="SelectedIndexChanged">
             <Columns>
        <asp:BoundField DataField="UserId" HeaderText="User Id" ItemStyle-Width="50" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Designation" HeaderText="Designation" ItemStyle-Width="200" />
        <asp:BoundField DataField="Department" HeaderText="Department" ItemStyle-Width="150" />
        <asp:TemplateField ItemStyle-Width="20px">
        <ItemTemplate>
            <asp:Image ID="Image1" Height="20px" Width="20px" Visible="false" runat="server" ImageUrl="~/images/btnyes.jpg" />
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
  
        </asp:GridView>
      
      
    <asp:LinkButton ID="lnkDummy" runat="server"></asp:LinkButton>
    </div>
    </form>

  • Now add the following code in your code window ::

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;

public partial class SelectingGridRow : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }

    private void BindData()
    {
        gvDetails.DataSource = this.getData();
        gvDetails.DataBind();
    }

    private DataTable getData()
    {
        if (ViewState["Details"] != null)
            return (DataTable)ViewState["Details"];

        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Designation", typeof(string));
        dt.Columns.Add("Department", typeof(string));

        DataRow dr = dt.NewRow();
        dr["UserId"] = 101;
        dr["Name"] = "Zaheer";
        dr["Designation"] = "Associate Technical Consultant";
        dr["Department"] = ".Net";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 12;
        dr["Name"] = "Anish";
        dr["Designation"] = "Technical Consultant";
        dr["Department"] = "CRM";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 113;
        dr["Name"] = "Manish";
        dr["Designation"] = "Navision Consultant";
        dr["Department"] = "Navision";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 4;
        dr["Name"] = "Ravish";
        dr["Designation"] = "Tech Lead";
        dr["Department"] = "CRM";
        dt.Rows.Add(dr);

        ViewState["Details"] = dt;
        return dt;
    }

// On clicking any row i am changing the back color and showing a Tick mark in a column

    protected void SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow row in gvDetails.Rows)
        {
            if (row.RowIndex == gvDetails.SelectedIndex)
            {
                //Response.Write("<script>alert('You have selected a row');</script>");
                System.Web.UI.WebControls.Image img = ((System.Web.UI.WebControls.Image)row.FindControl("Image1"));
                img.Visible = true;
                row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
                row.ToolTip = string.Empty;
            }
            else
            {
                System.Web.UI.WebControls.Image img = ((System.Web.UI.WebControls.Image)row.FindControl("Image1"));
                img.Visible = false;
                row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
                row.ToolTip = "Click to select row";
            }
        }
    }


// A JavaScript click event handler is attached to each row using "onclick" attribute. The "GetPostBackClientHyperlink" method accepts the Gridview instance as well as the command RowIndex of the row
// When "GetPostBackClientHyperlink"rendered this gets converted to the JavaScript __doPostBack method.

    protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType==DataControlRowType.DataRow)
        {
            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvDetails, "Select$" + e.Row.RowIndex);
            e.Row.ToolTip = "Click to select row";
        }
    }
}

Note: Set the EnableEventValidation to "False" in @PageDirective.

Comments

Popular posts from this blog

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

How to import CSV files into DataTable in C#

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

go to top image