Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

datagrid selected row back color

Posted on 2006-05-08
2
Medium Priority
?
651 Views
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.
0
Comment
Question by:reval1
1 Comment
 
LVL 28

Accepted Solution

by:
iboutchkine earned 750 total points
ID: 16630372
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 System.data.oleDb.OleDbConnection

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()



    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
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    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.SuspendLayout()
        '
        'DataGrid1
        '
        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
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(712, 333)
        Me.Controls.Add(Me.DataGrid1)
        Me.Name = "Form1"
        Me.Text = "Products"
        CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

#End Region

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



        MakeConnection()

        '================================================================
        '//---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)  




        MyConnection.Close()


    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
        MyCommand.Fill(dsData)
        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)

            Try
                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)

                Try
                    g.DrawString(s.Substring(0, maxChars), e.TextFont, foreBrush, bounds.X, bounds.Y + 2)
                Catch ex As Exception
                    Console.WriteLine(ex.Message.ToString())
                End Try
            Catch
            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
                e.BackBrush.Dispose()
            End If
            If e.ForeBrushDispose Then
                e.ForeBrush.Dispose()
            End If
            If e.TextFontDispose Then
                e.TextFont.Dispose()
            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)
            TableStyle.GridColumnStyles.Add(column)
        Next
        MyControl.TableStyles.Clear()
        MyControl.TableStyles.Add(TableStyle)

    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)
        Else
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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
        Get
            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

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…

571 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