Rahul Soni's blog

Never assume the obvious is true!

Dynamic Datagrid Series - 3.Highlighting Datagrid Rows when the mouse hovers over any row

Dynamic Datagrid Series - 3.Highlighting Datagrid Rows when the mouse hovers over any row

  • Comments 1

Requirement 3
=============
We have a formatted datagrid which is dynamically added on your page. Without doing much coding, we want to provide the functionality in such a way that whenever the mouse hovers over any row the color should change. Also, if we are using Row styles for Item and Alternate Item, the hovering of mouse should not disturb the original colors, i.e, the original should come back as soon as the mouse is out of that row.

Let's create a new ASP.NET Web Application under Visual Basic Projects called DataGridDemo3.
Add the following lines just after your <configuration> tag in the web.config. I will be working with the "pubs" database all the time. Better to have it in the web.config.

 <appSettings>
      <add key="ConnectionInfo" value="server=(local);database=Pubs;user id=sa;password="/>
 </appSettings>

1) Create a new Page called "HighLightRow.aspx"
2) Drag and drop a PlaceHolder control and change the ID to "PlaceHolder". Go to the code behind of this page and delete everything. Now paste the following...

Imports System.Data
Imports System.Data.SqlClient
'
Public Class HighLightRow
    Inherits System.Web.UI.Page
    '
#Region " Web Form Designer Generated Code "
    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    End Sub
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub
#End Region
    '
    Protected WithEvents PlaceHolder As System.Web.UI.WebControls.PlaceHolder
    Dim dg As New DataGrid()
    Dim strConn As String = ConfigurationSettings.AppSettings("ConnectionInfo")
    Dim strCommand As String = "select top 10 au_lname as Last_Name," & _
    " au_fname as First_Name, phone as Phone_Number, state as State, " & _
    "12345678 as Dummy_Number, 1234.56789 as Dummy_Currency, " & _
    "GetDate() as Dummy_Date from authors"
    '
    Private Sub Page_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs _
    ) Handles MyBase.Load
        '
        'Put user code to initialize the page here
        Dim tblData As DataTable
        tblData = GetData(strCommand, strConn)
        dg.DataSource = tblData
        dg.AutoGenerateColumns = False
        AddHandler dg.ItemCreated, AddressOf DataGrid_ItemCreated
        FormatColumns(tblData)
        dg.DataBind()
        PlaceHolder.Controls.Add(dg)
        FormatDataGrid()
    End Sub
    '
    Protected Sub DataGrid_ItemCreated( _
        ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs _
    )
        'Since we are using alternate colors and won't like to miss out on the colors,
        'we need to add the attributes such that it reverts back whatever color was used before.
        Dim Remainder As Integer
        Remainder = e.Item.ItemIndex Mod 2
        Select Case Remainder
            Case -1 'It is a header
            Case 0 'Item
                e.Item.Attributes.Add("OnMouseOver", "this.style.backgroundColor = 'beige';")
                e.Item.Attributes.Add("OnMouseOut", "this.style.backgroundColor = 'cyan';")
            Case 1  'Alternate Item
                e.Item.Attributes.Add("OnMouseOver", "this.style.backgroundColor = 'beige';")
                e.Item.Attributes.Add("OnMouseOut", "this.style.backgroundColor = '#CED8FD';")
        End Select
    End Sub
    '
    Private Sub FormatDataGrid()
        dg.CellPadding = 5
        dg.BorderColor = Color.Black
        'Set Font settings
        dg.Font.Name = "Arial"
        dg.Font.Size = New FontUnit(10)
        'Show Header and Footer
        dg.ShowHeader = True 'Default is true
        'Set Header Style
        dg.HeaderStyle.Font.Bold = True
        dg.HeaderStyle.BackColor = Color.DarkGray
        dg.HeaderStyle.ForeColor = Color.Black
        dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
        dg.HeaderStyle.VerticalAlign = VerticalAlign.Middle
        'Set Item Style
        dg.ItemStyle.BackColor = Color.Cyan
        dg.ItemStyle.ForeColor = Color.Black
        'Set Alternating Item Style
        dg.AlternatingItemStyle.BackColor = Color.FromArgb(206, 216, 253) 'In Hex = #CED8FD
        dg.AlternatingItemStyle.ForeColor = Color.Black
    End Sub
    '
    Private Sub FormatColumns(ByRef tblData As DataTable)
        Dim colDataColumn As DataColumn
        For Each colDataColumn In tblData.Columns()
            dg.Columns.Add(CreateBoundColumns(colDataColumn))
        Next
    End Sub
    '
    Private Function GetData(ByVal strCommand As String, _
        ByVal strConn As String _
    ) As DataTable
        Dim adpSQLAdapter As New SqlDataAdapter(strCommand, strConn)
        Dim tblData As New DataTable()
        adpSQLAdapter.Fill(tblData)
        Return tblData
    End Function
    '
    Private Function CreateBoundColumns( _
        ByRef colDataColumn As DataColumn _
    ) As DataGridColumn
        '
        Dim bndColumn As New BoundColumn()
        '
        bndColumn.DataField = colDataColumn.ColumnName
        bndColumn.HeaderText = colDataColumn.ColumnName.Replace("_", " ")
        bndColumn.DataFormatString = SetFormatString(colDataColumn)
        Return bndColumn
    End Function
    '
    Private Function SetFormatString( _
        ByRef colDataColumn As DataColumn _
    ) As String
        '
        Dim strDataType As String
        '
        Select Case colDataColumn.DataType.ToString()
            Case "System.Int32"
                strDataType = "{0:#,###}"
            Case "System.Decimal"
                strDataType = "{0:c}"
            Case "System.DateTime"
                strDataType = "{0:dd-mm-yyyy}"
            Case "System.String"
                strDataType = ""
            Case Else
                strDataType = ""
        End Select
        Return strDataType
    End Function
End Class

3) Open Solution Explorer, right click on "HighLightRow.aspx" and select "Set as Start Page" in the menu
4) Click on Debug -> Start and you should be able to see a table of Data from the Database which changes color whenever you hover your mouse on the row.

Attachment: HighLightRow.aspx.txt
  • Doen't work on Firefox Browser
Page 1 of 1 (1 items)
Leave a Comment
  • Please add 2 and 5 and type the answer here:
  • Post