Sunday, September 3, 2017

Asp.net Gridview: Change row color on mousehover

In this article I am going to explain how to change Gridview row color on mousehover in asp.net.

Description:
I am showing employees detail in Gridview data control. I want to change the color of row on mousehover.


Implementation:
We have many approaches to change the row color on mousehover code behind, through CSS and javascript.

HTML Markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Change Gridview row color on mousehover</title>
    <style type="text/css">            
               .Rowhighlightcolor
               {
                       background-color: #f5f5f5;
                       cursor: pointer;
               }
                  .Rowdefaultcolor
               {
                       background-color: #FFFFFF;
               }
              #GridView1 tr.rowHover:hover
                  {
                  background-color: #f5f5f5;
                  }

       </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" RowStyle-CssClass=" grdrowHover ">
            <Columns>
                <asp:BoundField HeaderText="Name" DataField="Name" NullDisplayText="-NA-">
                <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="Phone" HeaderText="Phone" NullDisplayText="-NA-">
                <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="Salary" HeaderText="Salary" NullDisplayText="-NA-">
                  <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                  <asp:BoundField DataField="Department" HeaderText="Department" NullDisplayText="-NA-">
                <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="EmailId" HeaderText="Email" NullDisplayText="-NA-">
                <HeaderStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:ImageField DataImageUrlField="ImagePath" ControlStyle-Height="100" ControlStyle-Width="100" NullDisplayText="-NA-">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
                </asp:ImageField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Add namespace

C# Code
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

VB.net Code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Bind gridview
Create a method to bind gridview and call it on page load.

C# Code
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Fillgrid();
        }
    }
    public void Fillgrid()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Employees", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch(Exception ex){}
    }

VB.net Code
  Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Fillgrid()
        End If
    End Sub
    Public Sub Fillgrid()
        Try
            Dim adp As New SqlDataAdapter("Select * from Employees", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            GridView1.DataSource = dt
            GridView1.DataBind()
        Catch ex As Exception
        End Try
    End Sub

1st approach:
Write the below given code on Rowdatabound event of gridview

C# Code
  protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            e.Row.Cells[i].ToolTip = e.Row.Cells[i].Text;
            e.Row.Attributes.Add("onMouseOver", "this.style.backgroundColor='#f1f3f5';");
            e.Row.Attributes.Add("OnMouseOut", "this.style.backgroundColor='#FFFFFF';");
        }      
    }


VB.net Code
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
     For i As Integer = 0 To e.Row.Cells.Count - 1
            e.Row.Cells(i).ToolTip = e.Row.Cells(i).Text
            e.Row.Attributes.Add("onMouseOver", "this.style.backgroundColor='#f1f3f5';")
            e.Row.Attributes.Add("OnMouseOut", "this.style.backgroundColor='#FFFFFF';")
        Next
    End Sub

2nd approach
Create CSS class and apply it on gridview.

CSS style:

    <style type="text/css">
              #GridView1 tr.grdrowHover:hover
                  {
                  background-color: #f5f5f5;
                  }

       </style>

Apply CSS class on Gridview

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" RowStyle-CssClass="grdrowHover">


3rd approach
Create CSS class and call it on code behind on Gridview Rowdatabound event.

CSS style:
    <style type="text/css">            
               .Rowhighlightcolor
               {
                       background-color: #f5f5f5;
                       cursor: pointer;
               }
                  .Rowdefaultcolor
               {
                       background-color: #FFFFFF;
               }
       </style>

C# code
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            e.Row.Cells[i].ToolTip = e.Row.Cells[i].Text;
            e.Row.Attributes.Add("onMouseOver", "this.className='Rowhighlightcolor';");
            e.Row.Attributes.Add("onmouseout", "this.className='Rowdefaultcolor';");
        }      
    }

VB.net code
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
     For i As Integer = 0 To e.Row.Cells.Count - 1
            e.Row.Attributes.Add("onMouseOver", "this.className='Rowhighlightcolor';")
            e.Row.Attributes.Add("onmouseout", "this.className='Rowdefaultcolor';")
        Next
    End Sub

4th approach
Create a Javascript function and apply the CSS class.

<style type="text/css">            
               .Rowhighlightcolor
               {
                       background-color: #f5f5f5;
                       cursor: pointer;
               }
                  .Rowdefaultcolor
               {
                       background-color: #FFFFFF;
               }

       </style>


    <script type="text/javascript">
        $(document).ready(function () {
            $('td').hover(function () {
                $('tr').each(function () {
                    $(this).removeClass('Rowhighlightcolor');
                });
                $(this).parent().addClass('Rowhighlightcolor');
            });
        });
    </script>


No comments:

Post a Comment