datagrid selected row back color

Posted on 2006-05-08
Last Modified: 2012-08-13
how to permanent change backcolor of  row on double click event in datagrid so that we can identify that those colored rows user has dbl clicked.
Question by:reval1
    1 Comment
    LVL 28

    Accepted Solution

    Found somewhere on the net

    'Nortwind.mdb in bin directory

    Imports System.Data
    Imports System.Windows
    Imports System.IO

    Public Class Form1
        Inherits System.Windows.Forms.Form
        Private dsData As System.Data.DataSet
        Private MyCommand As System.Data.OleDb.OleDbDataAdapter
        Private MyConnection As

    #Region " Windows Form Designer generated code "

        Public Sub New()

            'This call is required by the Windows Form Designer.

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents DataGrid1 As DataGrid
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.DataGrid1 = New System.Windows.Forms.DataGrid
            CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.DataGrid1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                        Or System.Windows.Forms.AnchorStyles.Left) _
                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.DataGrid1.DataMember = ""
            Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
            Me.DataGrid1.Location = New System.Drawing.Point(16, 8)
            Me.DataGrid1.Name = "DataGrid1"
            Me.DataGrid1.Size = New System.Drawing.Size(684, 312)
            Me.DataGrid1.TabIndex = 0
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(712, 333)
            Me.Name = "Form1"
            Me.Text = "Products"
            CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()

        End Sub

    #End Region

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


            '//---NEW MFG CLASS

            '//--Add this lines when your data connection is refreshed or changed
            Dim NewColorGrid As New MFGDataGridSubClass
            NewColorGrid.InitializeColorGrid(dsData, DataGrid1)        '//--InitializeColorGrid( 1st Parameter= Your DataSource, 2nd Paramenter= Your Datagrid)

            '//---ENDS MFG CLASS

            '//-- FYI:
            '//-- Use the 'ChangeRowColor_Event' Subroutine in the 'MFGDataGridSubClass Class'
            '//-- To configure the Color Validations.

            '//-- Its Safe to use multiple Grids with the same Class.

            '//-- Example:

            '-----        Dim NewColorGrid1 As New MFGDataGridSubClass
            '-----        NewColorGrid1.InitializeColorGrid(dsData, DataGrid1)  

            '-----        Dim NewColorGrid2 As New MFGDataGridSubClass
            '-----        NewColorGrid2.InitializeColorGrid(dsData, DataGrid2)  


        End Sub

        Private Sub MakeConnection()

            MyConnection = New System.Data.OleDb.OleDbConnection( _
              "provider=Microsoft.Jet.OLEDB.4.0; " & _
              "data source= " & Directory.GetCurrentDirectory & "\Northwind.MDB")

            MyCommand = New System.Data.OleDb.OleDbDataAdapter( _
                          "select * from Orders", MyConnection)

            dsData = New System.Data.DataSet
            DataGrid1.DataSource = dsData.Tables(0)

        End Sub

    End Class
    Class MFGDataGridSubClass.vb
    Option Explicit On

    Public Class MFGDataGridSubClass
        Inherits DataGridTextBoxColumn
        Private MyControl As DataGrid
        Private iColCount As Integer = 0
        Private iRowCount As Integer = 0
        Public TableStyle As New DataGridTableStyle
        Public Delegate Sub FormatCellEventHandler(ByVal sender As Object, ByVal e As DataGridFormatCellEventArgs)
        Public Event ColorChanged As FormatCellEventHandler

        'used to fire an event to retrieve formatting info
        'and then draw the cell with this formatting info
        Protected Overloads Overrides Sub Paint(ByVal g As System.Drawing.Graphics, ByVal bounds As System.Drawing.Rectangle, ByVal [source] As System.Windows.Forms.CurrencyManager, ByVal rowNum As Integer, ByVal backBrush As System.Drawing.Brush, ByVal foreBrush As System.Drawing.Brush, ByVal alignToRight As Boolean)
            Dim e As DataGridFormatCellEventArgs = Nothing

            'fire the formatting event
            Dim col As Integer = Me.DataGridTableStyle.GridColumnStyles.IndexOf(Me)
            e = New DataGridFormatCellEventArgs(rowNum, col, Me.GetColumnValueAtRow([source], rowNum))
            RaiseEvent ColorChanged(Me, e)

            Dim callBaseClass As Boolean = True

            If Not (e.BackBrush Is Nothing) Then
                backBrush = e.BackBrush
            End If
            If Not (e.ForeBrush Is Nothing) Then
                foreBrush = e.ForeBrush
            End If

            If Not (e.TextFont Is Nothing) Then
                g.FillRectangle(backBrush, bounds)

                    Dim charWidth As Integer = Fix(Math.Ceiling(g.MeasureString("c", e.TextFont, 20, StringFormat.GenericTypographic).Width))

                    Dim s As String = Me.GetColumnValueAtRow([source], rowNum).ToString()
                    Dim maxChars As Integer = Math.Min(s.Length, bounds.Width / charWidth)

                        g.DrawString(s.Substring(0, maxChars), e.TextFont, foreBrush, bounds.X, bounds.Y + 2)
                    Catch ex As Exception
                    End Try
                End Try
                callBaseClass = False

            End If

            If Not e.UseBaseClassDrawing Then
                callBaseClass = False
            End If
            If callBaseClass Then
                MyBase.Paint(g, bounds, [source], rowNum, backBrush, foreBrush, alignToRight)
            End If
            'clean up
            If Not (e Is Nothing) Then
                If e.BackBrushDispose Then
                End If
                If e.ForeBrushDispose Then
                End If
                If e.TextFontDispose Then
                End If
            End If
        End Sub 'Paint    

        Public Sub InitializeColorGrid(ByRef dsData As DataSet, ByRef dsDataGrid As DataGrid)
            Dim rCounter As Integer
            Dim column As MFGDataGridSubClass

            MyControl = dsDataGrid

            TableStyle.MappingName = dsData.Tables(0).TableName

            iColCount = dsData.Tables(0).Columns.Count - 1
            iRowCount = dsData.Tables(0).Rows.Count - 1

            For rCounter = 0 To iColCount
                column = New MFGDataGridSubClass
                column.MappingName = dsData.Tables(0).Columns(rCounter).ColumnName
                column.HeaderText = dsData.Tables(0).Columns(rCounter).ColumnName
                AddHandler column.ColorChanged, New MFGDataGridSubClass.FormatCellEventHandler(AddressOf ChangeRowColor_Event)

        End Sub

        Public Sub ChangeRowColor_Event(ByVal sender As Object, ByVal e As DataGridFormatCellEventArgs)

            If MyControl.IsSelected(e.Row) Then
                e.BackBrush = New SolidBrush(Color.Red)
                e.ForeBrush = New SolidBrush(Color.Pink)
                Select Case MyControl.Item(e.Row, iColCount)
                    Case "Mexico"
                        e.BackBrush = New SolidBrush(Color.Green)
                        e.ForeBrush = New SolidBrush(Color.White)
                    Case "USA"
                        e.BackBrush = New SolidBrush(Color.Blue)
                        e.ForeBrush = New SolidBrush(Color.Yellow)
                    Case "Germany"
                        e.BackBrush = New SolidBrush(Color.Orange)
                        e.ForeBrush = New SolidBrush(Color.OrangeRed)
                End Select
            End If
        End Sub

    End Class

    Public Class DataGridFormatCellEventArgs
        Inherits EventArgs

        Public Sub New(ByVal row As Integer, ByVal col As Integer, ByVal cellValue As Object)
            rowNum = row
            colNum = col
            fontVal = Nothing
            backBrushVal = Nothing
            foreBrushVal = Nothing
            fontDisposeVal = False
            backBrushDisposeVal = False
            foreBrushDisposeVal = False
            useBaseClassDrawingVal = True
            currentCellValueVal = cellValue
        End Sub 'New

        ' Holds the column number of the cell being painted.
        Public Property Column() As Integer
                Return colNum
            End Get
            Set(ByVal Value As Integer)
                colNum = Value
            End Set
        End Property

        ' Holds the row number of the cell being painted.
        Public Property Row() As Integer
                Return rowNum
            End Get
            Set(ByVal Value As Integer)
                rowNum = Value
            End Set
        End Property

        ' Holds the font to be used to draw text in the cell.
        Public Property TextFont() As Font
                Return fontVal
            End Get
            Set(ByVal Value As Font)
                fontVal = Value
            End Set
        End Property

        ' Holds the brush used to paint the cell's background.
        Public Property BackBrush() As Brush
                Return backBrushVal
            End Get
            Set(ByVal Value As Brush)
                backBrushVal = Value
            End Set
        End Property

        ' Holds the brush used to paint the text in the cell.
        Public Property ForeBrush() As Brush
                Return foreBrushVal
            End Get
            Set(ByVal Value As Brush)
                foreBrushVal = Value
            End Set
        End Property

        ' Set to true if the Dispose method of the TextFont
        '     should be called by the Paint override.
        Public Property TextFontDispose() As Boolean
                Return fontDisposeVal
            End Get
            Set(ByVal Value As Boolean)
                fontDisposeVal = Value
            End Set
        End Property

        ' Set to true if the Dispose method of the BackBrush
        '     should be called by the Paint override.
        Public Property BackBrushDispose() As Boolean
                Return backBrushDisposeVal
            End Get
            Set(ByVal Value As Boolean)
                BackBrushDispose = Value
            End Set
        End Property

        ' Set to true if the Dispose method of the ForeBrush
        '     should be called by the Paint override.
        Public Property ForeBrushDispose() As Boolean
                Return foreBrushDisposeVal
            End Get
            Set(ByVal Value As Boolean)
                ForeBrushDispose = Value
            End Set
        End Property

        ' Set to false if the MyBase.Paint method  
        '     should not be called in the Paint override.
        Public Property UseBaseClassDrawing() As Boolean
                Return useBaseClassDrawingVal
            End Get
            Set(ByVal Value As Boolean)
                useBaseClassDrawingVal = Value
            End Set
        End Property

        ' Holds the current cell value.
        Public ReadOnly Property CurrentCellValue() As Object
                Return currentCellValueVal
            End Get
        End Property

        ' Private fields to hold the public properties.
        Private colNum As Integer
        Private rowNum As Integer
        Private fontVal As Font
        Private backBrushVal As Brush
        Private foreBrushVal As Brush
        Private fontDisposeVal As Boolean
        Private backBrushDisposeVal As Boolean
        Private foreBrushDisposeVal As Boolean
        Private useBaseClassDrawingVal As Boolean
        Private currentCellValueVal As Object

    End Class


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Article by: Kraeven
    Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
    1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now