How to bind gridview and highlight gridview row on mouse over in asp.net


Bind and highlight gridview row on mouse over example  in asp.net
Click on image to enlarge
Introduction: In previous articles i explained how to  Highlight gridview row on mouse over using CSS in asp.net and  How to show tool tip message using CSS and HTML in asp.net website. and How to show Validation guidelines in web forms using JavaScript in Asp.net. In this post I will explain how to bind Gridview control with Sql server table and Highlight GridView row on mouse over with the help of GridView's RowDataBound event and JavaScript.



  •  Create a Database in SQL Server e.g. “MyDataBase” and create a table in that database and name it “EMPLOYEE” as shown in figure.
Binding gridview example in asp.net
Click on image to enlarge
Note: EMP_ID column is set to primary key and its Identity Specification is set to Yes as shown in figure above.  Insert some records in the table that you want to show in Gridview control.
  • In the web.config file create the connection string under <configuration> tag:
<connectionStrings>
    <add name="EmpCon" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and Initial catalog (i.e. Database name) as per your application.
  • In the <HEAD> tag of design page(default.aspx) create JavScript function as:
<script type="text/javascript">
        var oldgridcolor;
        function SetMouseOver(element) {
            oldgridcolor = element.style.backgroundColor;
            element.style.backgroundColor = '#ffeb95';
            element.style.cursor = 'pointer';
            element.style.textDecoration = 'underline';
        }
        function SetMouseOut(element) {
            element.style.backgroundColor = oldgridcolor;
            element.style.textDecoration = 'none';
        }
</script>
  • In the <BODY> tag of default.aspx page place a GridView Control as:
<fieldset style="width:230px;">
            <legend>Gridview Binding Example</legend>
            <asp:GridView ID="EmpGridView" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDataBound="EmpGridView_RowDataBound">    
         <AlternatingRowStyle BackColor="White" />
       <Columns>  
        <asp:BoundField DataField="EMP_NAME"  HeaderText="Name" />
        <asp:BoundField DataField="DEPT"  HeaderText="Department" />
        <asp:BoundField DataField="SALARY"  HeaderText="Salary" />  
      </Columns>
         <EditRowStyle BackColor="#2461BF" />
         <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
         <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
         <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
         <RowStyle BackColor="#EFF3FB" />
         <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
         <SortedAscendingCellStyle BackColor="#F5F7FB" />
         <SortedAscendingHeaderStyle BackColor="#6D95E1" />
         <SortedDescendingCellStyle BackColor="#E9EBEF" />
         <SortedDescendingHeaderStyle BackColor="#4870BE" />
 </asp:GridView>
        </fieldset>

C#.Net Code to bind gridview and highlight gridview row on mouse over
  • In the Code behind file(default.aspx.cs) write the code as:
First include following namespaces:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

and then write the code as:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmpGrid();
        }   
    }
    private void BindEmpGrid()
    {
        DataTable dt = new DataTable();
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpCon"].ConnectionString);
            SqlDataAdapter adp = new SqlDataAdapter("Select * from EMPLOYEE", con);
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                EmpGridView.DataSource = dt;
                EmpGridView.DataBind();
            }
            else
            {
                EmpGridView.DataSource = null;
                EmpGridView.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error Occured: " + ex.ToString());
        }
        finally
        {
            dt.Clear();
            dt.Dispose();
        }
    }
    protected void EmpGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "javascript:SetMouseOver(this)";
            e.Row.Attributes["onmouseout"] = "javascript:SetMouseOut(this)"; 
        }
    }

VB.Net Code to bind gridview and highlight gridview row on mouse over
  • In the Code behind file(default.aspx.vb) write the code as:
First import following namespaces:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

and then write the code as:

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindEmpGrid()
        End If
    End Sub
    Private Sub BindEmpGrid()
        Dim dt As New DataTable()
        Try
            Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("EmpCon").ConnectionString)
            Dim adp As New SqlDataAdapter("Select * from EMPLOYEE", con)
            adp.Fill(dt)

            If dt.Rows.Count > 0 Then
                EmpGridView.DataSource = dt
                EmpGridView.DataBind()
            Else
                EmpGridView.DataSource = Nothing
                EmpGridView.DataBind()
            End If
        Catch ex As Exception
            Response.Write("Error Occured: " & ex.ToString())
        Finally
            dt.Clear()
            dt.Dispose()
        End Try
    End Sub

    Protected Sub EmpGridView_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles EmpGridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            e.Row.Attributes("onmouseover") = "javascript:SetMouseOver(this)"
            e.Row.Attributes("onmouseout") = "javascript:SetMouseOut(this)"
        End If
    End Sub


Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..