Saturday, February 21, 2015

Highlight or 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.

01--Creating Users Table
02CREATE TABLE dbo.Users
03(
04UserId INT IDENTITY PRIMARY KEY,
05UserName VARCHAR(100),
06Country VARCHAR(100),
07MobileNo VARCHAR(100),
08JoinedDate DATE,
09)
10GO
11 
12--Inserting Sample records into Users table
13INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
14VALUES('Kanna','Chennai','India','2009-06-01')
15 
16INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
17VALUES('Pramod','California','USA','2010-06-01')
18 
19INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
20VALUES('Robert','Some City','Canada','2011-06-01')
21 
22INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
23VALUES('Saxena','Mumbai','India','2012-06-01')
24 
25INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
26VALUES('Bhoto','Tokyo','Japan','2013-06-01')
27 
28INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
29VALUES('John','Austin','Australia','2014-06-01')
30 
31INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
32VALUES('Anthony','Bristol','UK','2015-06-01')
33 
34INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
35VALUES('Azhimo','City 1','Spain','2014-06-01')
36 
37INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
38VALUES('Bansal','Bangalore','India','2013-06-01')
39 
40INSERT INTO Users(UserName,Country,MobileNo,JoinedDate)
41VALUES('Gupta','Delhi','India','2012-06-01')
42GO
43 
44-- Procedure to fetch user details from users table
45CREATE PROC dbo.GetUsersDetail
46AS
47BEGIN
48SET NOCOUNT ON
49 SELECT UserId,UserName,Country,MobileNo,JoinedDate FROM dbo.Users
50SET NOCOUNT OFF
51END
52GO

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.

01<title>Highlight Gridview Row On MouseOver in C#.Net,
02 
03    ASP.Net VB.Net using CSS by .NetPickles</title>
04<style type="text/css">
05    .onmouseout {
06        background-color: white;
07    }
08 
09    .onmouseover {
10        background-color: green !important;
11    }
12</style>
13 
14 
15<form id="myForm" runat="server">
16    <div>
17        <h2>
18Highlight Gridview Row On MouseOver in
19C#.Net,
20            ASP.Net VB.Net using CSS</h2>
21<asp:gridview backcolor="White" bordercolor="#CC9966" borderstyle="None"borderwidth="1px" cellpadding="4" id="GridViewUsers"onrowcreated="GridViewUsers_RowCreated" runat="server">
22            <headerstyle backcolor="#990000" font-bold="True" forecolor="#FFFFCC">
23        </headerstyle></asp:gridview>
24    </div>
25</form>

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: 
1<connectionstrings>
2  <add connectionstring="Data Source=local; Initial Catalog=mydb; User ID=SA;password=mypassword;" name="mydsn">
3</add></connectionstrings>

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

C#.Net: 
1using System.Data;
2using System.Data.SqlClient;
3using System.Configuration;

VB.Net: 
1Imports System.Data
2Imports System.Data.SqlClient
3Imports 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: 
01protected void Page_Load(object sender, EventArgs e)
02{
03try
04{
05    //read connection string from web.config
06    string connectionString = ConfigurationManager.ConnectionStrings["mydsn"].ConnectionString;
07    using (SqlConnection conn = new SqlConnection(connectionString))
08    {
09        using (SqlCommand cmd = new SqlCommand())
10        {
11            //Setting connection and command text to command object
12            cmd.Connection = conn;
13            cmd.CommandText = "dbo.GetUsersDetail";
14            cmd.CommandType = CommandType.StoredProcedure;
15 
16            //Filling dataset with data from users table
17            DataSet customers = new DataSet();
18            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
19            adapter.Fill(customers, "UsersDetails");
20 
21            //Binding data to grid view
22            GridViewUsers.DataSource = customers.Tables["UsersDetails"];
23            GridViewUsers.DataBind();
24        }
25    }
26}
27catch (Exception ex)
28{
29    // handle error
30}
31}

VB.NET
01Protected Sub Page_Load(sender As Object, e As EventArgs)
02 Try
03  'read connection string from web.config
04  Dim connectionString As String = ConfigurationManager.ConnectionStrings("mydsn").ConnectionString
05  Using conn As New SqlConnection(connectionString)
06   Using cmd As New SqlCommand()
07    'Setting connection and command text to command object
08    cmd.Connection = conn
09    cmd.CommandText = "dbo.GetUsersDetail"
10    cmd.CommandType = CommandType.StoredProcedure
11 
12    'Filling dataset with data from users table
13    Dim customers As New DataSet()
14    Dim adapter As New SqlDataAdapter(cmd)
15    adapter.Fill(customers, "UsersDetails")
16 
17    'Binding data to grid view
18    GridViewUsers.DataSource = customers.Tables("UsersDetails")
19    GridViewUsers.DataBind()
20   End Using
21  End Using
22   ' handle error
23 Catch ex As Exception
24 End Try
25End 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: 
01protected void GridViewUsers_RowCreated(object sender, GridViewRowEventArgs e)
02{
03    // Checking whether it is a datarow. Since it is not
04    // applicable to header and footer row
05    if (e.Row.RowType == DataControlRowType.DataRow)
06    {
07        //setting class for onmouseover event
08        e.Row.Attributes.Add("onmouseover""this.className='onmouseover'");
09        //setting class for onmouseout event
10        e.Row.Attributes.Add("onmouseout""this.className='onmouseout'");
11    }
12}

VB.Net: 
01Protected Sub GridViewUsers_RowCreated(sender As Object, e As GridViewRowEventArgs)
02 ' Checking whether it is a datarow. Since it is not
03 ' applicable to header and footer row
04 If e.Row.RowType = DataControlRowType.DataRow Then
05  'setting class for onmouseover event
06  e.Row.Attributes.Add("onmouseover""this.className='onmouseover'")
07  'setting class for onmouseout event
08  e.Row.Attributes.Add("onmouseout""this.className='onmouseout'")
09 End If
10End 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

 Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work, you can appreciate by leaving your comments. Stay tuned and stay connected for more technical updates."

No comments:

Post a Comment