Skip to main content

Highlight,change color of row on mouseover in grid view using CSS - C#.Net ASP.Net VB.Net

In this article i am going to explain about how to highlight/change color on mouse over in grid view using CSS. This is achieved by setting the different class on mouseover and mouseout event on the datarow of gridview. This can be acieved using the OnRowCreated event of the gridview.



For explanation purpose i have created a table called Users in my local database and inserted some sample records. And also i have created a procedure called GetUsersDetail which will return all the users detail from the users table. below is the sql script used.

--Creating Users Table
CREATE TABLE dbo.Users
(
UserId INT IDENTITY PRIMARY KEY,
UserName VARCHAR(100),
Country VARCHAR(100),
MobileNo VARCHAR(100),
JoinedDate DATE,
)
GO

--Inserting Sample records into Users table
INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Kanna','Chennai','India','2009-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Pramod','California','USA','2010-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Robert','Some City','Canada','2011-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Saxena','Mumbai','India','2012-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Bhoto','Tokyo','Japan','2013-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('John','Austin','Australia','2014-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Anthony','Bristol','UK','2015-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Azhimo','City 1','Spain','2014-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Bansal','Bangalore','India','2013-06-01')

INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
VALUES('Gupta','Delhi','India','2012-06-01')
GO

-- Procedure to fetch user details from users table
CREATE PROC dbo.GetUsersDetail
AS
BEGIN
SET NOCOUNT ON
 SELECT UserId,UserName,Country,MobileNo,JoinedDate FROM dbo.Users
SET NOCOUNT OFF
END
GO

Now open the visual studio and create a new website. In your default.aspx page drag and drop the GridView control from the toolbox and set the AutoGenerateColumns property to true to bind the columns returned from the procedure. And also i have added event handler for OnRowCreated event. Html markup is given below.


Highlight Gridview Row On MouseOver in C#.Net,<br />
    ASP.Net VB.Net using CSS by .NetPickles



Highlight Gridview Row On MouseOver in C#.Net, ASP.Net VB.Net using CSS


If you look into the html markup i have created two classes called onmouseout and onmouseover. Which is used to set to the grid view row events.

Now i have added my connection string information in the web.config file like below.

Connection String:

  


Now please import the below mentioned namespaces in your code behind file to make use of it.

C#.Net:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.Net:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

After that i have written the code to fetch data from users table on page load event. Below is the code used

C#.Net:
protected void Page_Load(object sender, EventArgs e)
{
try
{
    //read connection string from web.config
    string connectionString = ConfigurationManager.ConnectionStrings["mydsn"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            //Setting connection and command text to command object
            cmd.Connection = conn;
            cmd.CommandText = "dbo.GetUsersDetail";
            cmd.CommandType = CommandType.StoredProcedure;

            //Filling dataset with data from users table
            DataSet customers = new DataSet();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            adapter.Fill(customers, "UsersDetails");

            //Binding data to grid view
            GridViewUsers.DataSource = customers.Tables["UsersDetails"];
            GridViewUsers.DataBind();
        }
    }
}
catch (Exception ex)
{
    // handle error
}
}

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Try
  'read connection string from web.config
  Dim connectionString As String = ConfigurationManager.ConnectionStrings("mydsn").ConnectionString
  Using conn As New SqlConnection(connectionString)
   Using cmd As New SqlCommand()
    'Setting connection and command text to command object
    cmd.Connection = conn
    cmd.CommandText = "dbo.GetUsersDetail"
    cmd.CommandType = CommandType.StoredProcedure

    'Filling dataset with data from users table
    Dim customers As New DataSet()
    Dim adapter As New SqlDataAdapter(cmd)
    adapter.Fill(customers, "UsersDetails")

    'Binding data to grid view
    GridViewUsers.DataSource = customers.Tables("UsersDetails")
    GridViewUsers.DataBind()
   End Using
  End Using
   ' handle error
 Catch ex As Exception
 End Try
End Sub

Now if you run the code you will get the output as given below...
Output of Highlight,change color of row on mouseover in grid view using CSS - C#.Net ASP.Net VB.Net
But i would like to highlight or change the colour of the current row on mouse over event. To achieve this i have written the following code in OnRowCreated event of the gridview. I have simply set two different classes on onmouseover and onmouseout events. The classes will change the backgroud color or highlight the specified row by specified colour.

C#.Net:
protected void GridViewUsers_RowCreated(object sender, GridViewRowEventArgs e)
{
    // Checking whether it is a datarow. Since it is not 
    // applicable to header and footer row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //setting class for onmouseover event
        e.Row.Attributes.Add("onmouseover", "this.className='onmouseover'");
        //setting class for onmouseout event
        e.Row.Attributes.Add("onmouseout", "this.className='onmouseout'");
    }
}

VB.Net:
Protected Sub GridViewUsers_RowCreated(sender As Object, e As GridViewRowEventArgs)
 ' Checking whether it is a datarow. Since it is not 
 ' applicable to header and footer row
 If e.Row.RowType = DataControlRowType.DataRow Then
  'setting class for onmouseover event
  e.Row.Attributes.Add("onmouseover", "this.className='onmouseover'")
  'setting class for onmouseout event
  e.Row.Attributes.Add("onmouseout", "this.className='onmouseout'")
 End If
End Sub

Now while moving the cursor over the grid view row the row will get highlighted.
Output of Highlight,change color of row on mouseover in grid view using CSS - C#.Net ASP.Net VB.Net
Download C#.Net,ASP.Net & VB.Net Sourcecode to Highlight,change color of row on mouseover in grid view using CSS:
 Highlight,change color of row on mouseover in grid view using CSS C#.Net VB.Net ASP.Net

You may also like:
  1. Binding Gridview in Asp.net
  2. C#.Net - Programmatically Group Gridview Column Headers in ASP.Net,VB.Net 
  3. Fill Datatable and Bind GridView Using Data Reader in ASP.Net C#.Net VB.Net 
  4. Form hyperlink with querystring inside gridview in ASP.Net/C#.Net
  5. How to show confirm message while deleting grid view row.
  6. Select deselect all checkboxes in grid view using javascript
  7. Auto redirect page using javascript
  8. Auto refresh page using javascript


Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw