Link to home
Start Free TrialLog in
Avatar of munir_mustafa
munir_mustafa

asked on

Datagridview multi color cell text

How I can change the datagridview cell text color in multicolr text
Avatar of Howard Cantrell
Howard Cantrell
Flag of United States of America image

Here is some code that I use. You can change the settings to do other colors

'FORM 1

Option Explicit On

Imports Microsoft.VisualBasic
Imports System
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Common
Imports System.Data.OleDb
Imports System.Drawing
Imports System.Windows.Forms
Public Class DataGridColor
    Inherits Form
    Private WithEvents dataGrid1 As DataGrid
    Private components As Container
    Public Sub New()
        MyBase.New()
        '
        ' Required for Windows Form Designer support
        '
        InitializeComponent()

    End Sub
    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
    Private Sub InitializeComponent()

        Me.dataGrid1 = New System.Windows.Forms.DataGrid
        CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        ' dataGrid1
        '
        Me.dataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right)
        Me.dataGrid1.DataMember = ""
        Me.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dataGrid1.Location = New System.Drawing.Point(24, 24)
        Me.dataGrid1.Name = "dataGrid1"
        Me.dataGrid1.Size = New System.Drawing.Size(448, 280)
        Me.dataGrid1.TabIndex = 0
        '
        ' DataGridColor   Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(504, 341)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.dataGrid1})
        Me.Name = "DataGridColor"
        Me.Text = "DataGridColor"
        AddHandler Me.Load, New System.EventHandler(AddressOf Form1_Load)
        CType(Me.dataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub
    <STAThread()> _
    Public Shared Sub Main()

        Application.Run(New DataGridColor)

    End Sub
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Set the connection and sql strings
        ' assumes your mdb file is in your root
        Dim connString As String
        connString = "Provider=Microsoft.JET.OLEDB.4.0;data source=C:\OLD D DIR\Visual Studio Projects\TestArea\Northwind.mdb"
        Dim sqlString As String
        sqlString = "SELECT * FROM customers"
        Dim dataAdapter As OleDbDataAdapter
        dataAdapter = Nothing
        Dim _dataSet As DataSet
        _dataSet = Nothing
        ' Create a table style that will hold the new column style
        ' that we set and also tie it to our customer's table from our DB
        Try
            ' Connection object
            Dim connection As OleDbConnection
            connection = New OleDbConnection(connString)
            ' Create data adapter object
            dataAdapter = New OleDbDataAdapter(sqlString, connection)
            ' Create a dataset object and fill with data using data adapter's Fill method
            _dataSet = New DataSet
            dataAdapter.Fill(_dataSet, "customers")
            connection.Close()
        Catch ex As Exception
            MessageBox.Show(((((("Problem with DB access-" & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(10) & "   connection: " + connString) _
                            + "" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & "            query: ") _
                            + sqlString) _
                            + "" & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10) & Microsoft.VisualBasic.ChrW(13) & Microsoft.VisualBasic.ChrW(10)) _
                            + ex.ToString))
            Me.Close()
            Return
        End Try
        Dim tableStyle As DataGridTableStyle
        tableStyle = New DataGridTableStyle
        tableStyle.MappingName = "customers"
        ' since the dataset has things like field name and number of columns,
        ' we will use those to create new columnstyles for the columns in our DB table
        Dim numCols As Integer
        numCols = _dataSet.Tables("customers").Columns.Count
        Dim aColumnTextColumn As DataGridColoredTextBoxColumn
        Dim i As Integer
        i = 0

        Do While (i < numCols)
            aColumnTextColumn = New DataGridColoredTextBoxColumn
            aColumnTextColumn.HeaderText = _dataSet.Tables("customers").Columns(i).ColumnName
            aColumnTextColumn.MappingName = _dataSet.Tables("customers").Columns(i).ColumnName
            tableStyle.GridColumnStyles.Add(aColumnTextColumn)
            i += 1

        Loop
        ' make the dataGrid use our new tablestyle and bind it to our table
        dataGrid1.TableStyles.Clear()
        dataGrid1.TableStyles.Add(tableStyle)
        dataGrid1.DataSource = _dataSet.Tables("customers")

    End Sub
    Private Sub DataGrid1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles dataGrid1.Paint
        ''Extra Code
        ''column captions would run vertically
        'Dim gg As New StringFormat
        'gg.FormatFlags = StringFormatFlags.DirectionVertical
        'For ff As Integer = 0 To 10 'dt.Columns.Count - 1
        '    Dim x As Rectangle = dataGrid1.GetCellBounds(0, ff)
        '    x.Y = 22
        '    x.Height += 32

        '    e.Graphics.FillRectangle(New SolidBrush(dataGrid1.HeaderBackColor), x)
        '    e.Graphics.DrawString(CType(dataGrid1.DataSource, DataTable).Columns(ff).ToString(), dataGrid1.Font, New SolidBrush(Color.Black), x.X + 2, x.Y + 1, gg)

        'Next
    End Sub
End Class


'CLASS

Option Explicit On

Imports Microsoft.VisualBasic
Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Public Class DataGridColoredTextBoxColumn
    Inherits DataGridTextBoxColumn
    Public Sub New()
        'Warning: Implementation not found
    End Sub
    Protected Overloads Overrides Sub Paint(ByVal g As Graphics, ByVal bounds As Rectangle, ByVal source As CurrencyManager, ByVal rowNum As Integer, ByVal backBrush As Brush, ByVal foreBrush As Brush, ByVal alignToRight As Boolean)

        ' the idea is to conditionally set the foreBrush and/or backbrush
        ' depending upon some crireria on the cell value
        ' Here, we color anything that begins with a letter higher than 'F'
        Try
            Dim o As Object
            o = Me.GetColumnValueAtRow(source, rowNum)
            If (Not (o) Is Nothing) Then
                Dim c As Char
                c = CType(o, String).Substring(0, 1)
                If (c > "F") Then                        '<---- change colors HERE
                    backBrush = New SolidBrush(Color.Pink)
                    foreBrush = New SolidBrush(Color.White)
                End If
                'Use for numeric
                'o = CInt(o)
                'If (o <= 0) Then
                '    backBrush = New SolidBrush(Color.White)
                '    foreBrush = New SolidBrush(Color.Red)
                'End If
            End If
        Catch ex As Exception
            ' empty catch
        Finally
            ' make sure the base class gets called to do the drawing with
            ' the possibly changed brushes
            MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
        End Try

    End Sub

End Class
Avatar of munir_mustafa
munir_mustafa

ASKER

its working good but my question was DataGridView with  multicolor text in cell like
for e.g in a cell  "MUNIR" FIRST 3 CHARECTERS IN RED AND REAMAINING 2 IN GREEN
.
ASKER CERTIFIED SOLUTION
Avatar of Howard Cantrell
Howard Cantrell
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial