Solved

Datagridview multi color cell text

Posted on 2007-03-28
6
9,605 Views
Last Modified: 2013-12-26
How I can change the datagridview cell text color in multicolr text
0
Comment
Question by:munir_mustafa
  • 2
6 Comments
 
LVL 27

Expert Comment

by:planocz
ID: 18813468
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
0
 

Author Comment

by:munir_mustafa
ID: 18818052
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
.
0
 
LVL 27

Accepted Solution

by:
planocz earned 50 total points
ID: 18821357
I have not been able to find a way to just do the text color.
So Look at this app. that I made that I use with datgrids.

'FORM 1
Imports System.Data
Imports System.Drawing.Graphics

Public Class frmComBuilder
    Inherits System.Windows.Forms.Form
    Dim bHit As Boolean

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

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

        'Add any initialization after the InitializeComponent() call
        Me.Top = 0
        Me.Left = 100
        InitializeDataBase()
        Me.Show()
    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 dgInventory As System.Windows.Forms.DataGrid
    Friend WithEvents cmdExit As System.Windows.Forms.Button
    Friend WithEvents cmdOk As System.Windows.Forms.Button
    Friend WithEvents cmdAdd As System.Windows.Forms.Button
    Friend WithEvents cmdDelete As System.Windows.Forms.Button
    Friend WithEvents cmdUpdate As System.Windows.Forms.Button
    Friend WithEvents lblTable As System.Windows.Forms.Label
    Friend WithEvents lblQty As System.Windows.Forms.Label
    Friend WithEvents lblDescription As System.Windows.Forms.Label
    Friend WithEvents txtQty As System.Windows.Forms.TextBox
    Friend WithEvents txtDescription As System.Windows.Forms.TextBox
    Friend WithEvents ToolTip As System.Windows.Forms.ToolTip
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.dgInventory = New System.Windows.Forms.DataGrid
        Me.cmdExit = New System.Windows.Forms.Button
        Me.cmdOk = New System.Windows.Forms.Button
        Me.cmdAdd = New System.Windows.Forms.Button
        Me.cmdDelete = New System.Windows.Forms.Button
        Me.cmdUpdate = New System.Windows.Forms.Button
        Me.lblTable = New System.Windows.Forms.Label
        Me.lblQty = New System.Windows.Forms.Label
        Me.lblDescription = New System.Windows.Forms.Label
        Me.txtQty = New System.Windows.Forms.TextBox
        Me.txtDescription = New System.Windows.Forms.TextBox
        Me.ToolTip = New System.Windows.Forms.ToolTip(Me.components)
        CType(Me.dgInventory, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'dgInventory
        '
        Me.dgInventory.CaptionVisible = False
        Me.dgInventory.DataMember = ""
        Me.dgInventory.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dgInventory.Location = New System.Drawing.Point(16, 100)
        Me.dgInventory.Name = "dgInventory"
        Me.dgInventory.Size = New System.Drawing.Size(456, 196)
        Me.dgInventory.TabIndex = 0
        '
        'cmdExit
        '
        Me.cmdExit.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdExit.Location = New System.Drawing.Point(104, 312)
        Me.cmdExit.Name = "cmdExit"
        Me.cmdExit.Size = New System.Drawing.Size(68, 32)
        Me.cmdExit.TabIndex = 1
        Me.cmdExit.Text = "&Exit"
        '
        'cmdOk
        '
        Me.cmdOk.Enabled = False
        Me.cmdOk.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdOk.Location = New System.Drawing.Point(16, 312)
        Me.cmdOk.Name = "cmdOk"
        Me.cmdOk.Size = New System.Drawing.Size(72, 32)
        Me.cmdOk.TabIndex = 2
        Me.cmdOk.Text = "&Ok"
        '
        'cmdAdd
        '
        Me.cmdAdd.Enabled = False
        Me.cmdAdd.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdAdd.Location = New System.Drawing.Point(184, 312)
        Me.cmdAdd.Name = "cmdAdd"
        Me.cmdAdd.Size = New System.Drawing.Size(72, 32)
        Me.cmdAdd.TabIndex = 3
        Me.cmdAdd.Text = "&Add"
        '
        'cmdDelete
        '
        Me.cmdDelete.Enabled = False
        Me.cmdDelete.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdDelete.Location = New System.Drawing.Point(268, 312)
        Me.cmdDelete.Name = "cmdDelete"
        Me.cmdDelete.Size = New System.Drawing.Size(72, 32)
        Me.cmdDelete.TabIndex = 4
        Me.cmdDelete.Text = "&Delete"
        '
        'cmdUpdate
        '
        Me.cmdUpdate.Enabled = False
        Me.cmdUpdate.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdUpdate.Location = New System.Drawing.Point(356, 312)
        Me.cmdUpdate.Name = "cmdUpdate"
        Me.cmdUpdate.Size = New System.Drawing.Size(80, 32)
        Me.cmdUpdate.TabIndex = 5
        Me.cmdUpdate.Text = "&UpDate"
        '
        'lblTable
        '
        Me.lblTable.Font = New System.Drawing.Font("Times New Roman", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblTable.Location = New System.Drawing.Point(28, 16)
        Me.lblTable.Name = "lblTable"
        Me.lblTable.Size = New System.Drawing.Size(412, 28)
        Me.lblTable.TabIndex = 6
        '
        'lblQty
        '
        Me.lblQty.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblQty.Location = New System.Drawing.Point(24, 68)
        Me.lblQty.Name = "lblQty"
        Me.lblQty.Size = New System.Drawing.Size(84, 16)
        Me.lblQty.TabIndex = 7
        Me.lblQty.Text = "Qty. On Hand:"
        '
        'lblDescription
        '
        Me.lblDescription.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblDescription.Location = New System.Drawing.Point(192, 68)
        Me.lblDescription.Name = "lblDescription"
        Me.lblDescription.Size = New System.Drawing.Size(76, 16)
        Me.lblDescription.TabIndex = 8
        Me.lblDescription.Text = "Description:"
        '
        'txtQty
        '
        Me.txtQty.Location = New System.Drawing.Point(112, 64)
        Me.txtQty.Name = "txtQty"
        Me.txtQty.Size = New System.Drawing.Size(48, 20)
        Me.txtQty.TabIndex = 9
        Me.txtQty.Text = ""
        '
        'txtDescription
        '
        Me.txtDescription.Location = New System.Drawing.Point(268, 64)
        Me.txtDescription.Name = "txtDescription"
        Me.txtDescription.ReadOnly = True
        Me.txtDescription.Size = New System.Drawing.Size(336, 20)
        Me.txtDescription.TabIndex = 10
        Me.txtDescription.Text = ""
        '
        'ToolTip
        '
        Me.ToolTip.AutomaticDelay = 200
        Me.ToolTip.AutoPopDelay = 200
        Me.ToolTip.InitialDelay = 200
        Me.ToolTip.ReshowDelay = 40
        '
        'frmComBuilder
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(488, 346)
        Me.Controls.Add(Me.txtDescription)
        Me.Controls.Add(Me.txtQty)
        Me.Controls.Add(Me.lblDescription)
        Me.Controls.Add(Me.lblQty)
        Me.Controls.Add(Me.lblTable)
        Me.Controls.Add(Me.cmdUpdate)
        Me.Controls.Add(Me.cmdDelete)
        Me.Controls.Add(Me.cmdAdd)
        Me.Controls.Add(Me.cmdOk)
        Me.Controls.Add(Me.cmdExit)
        Me.Controls.Add(Me.dgInventory)
        Me.MaximizeBox = False
        Me.Name = "frmComBuilder"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "frmEditInventory"
        CType(Me.dgInventory, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub
#End Region
    Private Sub InitializeDataBase()
        Cursor.Current = Cursors.WaitCursor
        '*********** FOR ADO.NET **********************
        Dim sSQL As String = "SELECT * FROM " & sTableName
        AccessConnection(sSQL)

        Dim cb As System.Data.OleDb.OleDbCommandBuilder
        ' Optional command builder which automates the process of building each command
        ' by hand. This only works if the SelectCommand issued to the data
        ' adapter contains a primary key. USE EITHER ONE, BUT NOT BOTH
        ' Use cb.GetUpdateCommand.CommandText to view auto-generated SQL statements
        cb = New System.Data.OleDb.OleDbCommandBuilder(myDataAdapter)
        Dim mystr As String = cb.GetUpdateCommand.CommandText
        Dim val As Integer = cb.GetUpdateCommand.Parameters.Count

        ' Bind DataGrid control to this dataset            
        dgInventory.SetDataBinding(ds, sTableName)

        FillDataGrid()
        Cursor.Current = Cursors.Default
    End Sub
    Private Sub FillDataGrid()
        Dim sDescription As String

        dgInventory.DataSource = ds.Tables(sTableName)

        With grdTableStyle1
            .AlternatingBackColor = Color.GhostWhite
            .BackColor = Color.GhostWhite
            .ForeColor = Color.MidnightBlue
            .GridLineColor = Color.RoyalBlue
            .HeaderBackColor = Color.MidnightBlue
            .HeaderFont = New Font("Tahoma", 8.0!, FontStyle.Bold)
            .HeaderForeColor = Color.Lavender
            .SelectionBackColor = Color.Teal
            .SelectionForeColor = Color.PaleGreen
            ' Do not forget to set the MappingName property.
            ' Without this, the DataGridTableStyle properties
            ' and any associated DataGridColumnStyle objects
            ' will have no effect.
            .MappingName = sTableName
            .PreferredColumnWidth = 125
            .PreferredRowHeight = 16
        End With
        Dim grdColStyle1 As New DataGridTextBoxColumn
        With grdColStyle1
            .HeaderText = "ID"
            .MappingName = "ContactID"
            .Width = 40
            .ReadOnly = True
        End With

        With grdColStyle2
            .HeaderText = "Name"
            .MappingName = "Name"
            AddHandler grdColStyle2.TextBox.TextChanged, AddressOf dataGrid_TextChanged
            'test with
            iTag = 0
            Select Case iTag
                Case 0
                    sDescription = "Contacts"
                    .Width = 150
                Case 1
                    sDescription = "Music Material"
                    .Width = 450
            End Select
            Me.dgInventory.Width = (260 + .Width)
            Me.Width = Me.dgInventory.Width + 50
        End With

        With grdColStyle3
            .HeaderText = "On Hand"
            .MappingName = "OnHand"
            .Width = 60
            AddHandler grdColStyle3.TextBox.TextChanged, AddressOf dataGrid_TextChanged
        End With

        Dim grdColStyle4 As New DataGridTextBoxColumn
        With grdColStyle4
            .HeaderText = "Last Change Date"
            .MappingName = "LastChange"
            .Width = 120
            .ReadOnly = True
        End With
        Me.Text = sTableName
        Me.lblTable.Text = sDescription
        Me.txtDescription.Width = (Me.dgInventory.Width - 250)
        ' Add the style objects to the table style's collection of
        ' column styles. Without this the styles do not take effect.        
        grdTableStyle1.GridColumnStyles.AddRange _
            (New DataGridColumnStyle() {grdColStyle1, grdColStyle2, grdColStyle3, grdColStyle4})

        dgInventory.TableStyles.Add(grdTableStyle1)

        dgInventory.Select(0)

        txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
        txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
    End Sub
#Region " My Click Events Code "
    Private Sub cmdOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOk.Click
        '*****************
        'BEGIN EDIT CODE go get primary key
        Dim pk(0) As DataColumn
        pk(0) = ds.Tables(sTableName).Columns("ContactID")
        ds.Tables(sTableName).PrimaryKey = pk

        '********* Use this for single edit mode **************
        'CurRow = DS.Tables("Inventory_" & sTableName).Rows.Find(dgInventory.Item(dgInventory.CurrentRowIndex, 0))
        'CurRow.BeginEdit()
        'CurRow("OnHand") = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
        'CurRow("Description") = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
        'CurRow.EndEdit()
        'MsgBox("Record edited successfully")
        'CurRow.AcceptChanges()
        'myDataAdapter.Update(DS.Tables("Inventory_" & sTableName))
        'END EDIT CODE  
        '**********************************************
        '********* Edits the whole datagrid ************
        Dim icnt As Short = 0
        For Each CurRow In ds.Tables(sTableName).Rows
            CurRow.BeginEdit()
            CurRow("OnHand") = dgInventory.Item(icnt, 2)
            CurRow("Name") = dgInventory.Item(icnt, 1)
            icnt += 1
            CurRow.EndEdit()
        Next
        myDataAdapter.Update(ds.Tables(sTableName))
        MsgBox("Records edited successfully")
        dgInventory.Refresh()
        cmdUpdate.Enabled = False
        cmdAdd.Enabled = False
        cmdDelete.Enabled = False
        cmdOk.Enabled = False
    End Sub
    Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
        dgInventory.ReadOnly = False
        Me.BindingContext(DS, sTableName).Position = DS.Tables(sTableName).Rows.Count - 1
        '     "To save your changes to the Windows Forms DataGrid, press 'update'."
        ' dgInventory.Refresh()
        cmdUpdate_Click(sender, e)
    End Sub
    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
        DS.Tables(sTableName).Rows(Me.BindingContext(DS, sTableName).Position).Delete()
        'DS.Tables(sTableName).Rows.Item(dgInventory.CurrentRowIndex).Delete()
        'lblInfo.Text = To save your changes you must click 'Update'."
        cmdUpdate_Click(sender, e)
    End Sub
    Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
        Try
            myDataAdapter.Update(DS, sTableName)
            '  dg.ReadOnly = True
            'lblInfo.Text = "Changes to the Windows Forms DataGrid have been saved.
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try
        MsgBox("Records edited successfully")
        ' Create and fill dataset
        ResetGridColor()
        DS.Clear()
        DS = New DataSet(sTableName)
        myDataAdapter.Fill(DS, sTableName)
        ' Bind DataGrid control to this dataset            
        dgInventory.SetDataBinding(DS, sTableName)
        dgInventory.Refresh()
        cmdOk.Enabled = True
        cmdUpdate.Enabled = False
    End Sub
    Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
        ''    Conn.Close()
        ' Determine the active child form.
        'Dim activeChild As Form = Me.ActiveMdiChild
        'activeChild = ActiveForm
        '' If there is an active child form, find the active control, which
        '' in this example should be a RichTextBox.
        'If (activeChild Is Nothing) Then
        '    Try
        '        ' If activeChild.Name = "frmInventory" Then
        '        activeChild.WindowState = FormWindowState.Minimized
        '        activeChild.Show()
        '        '  End If
        '    Catch
        '        MessageBox.Show("You need to select a RichTextBox.")
        '    End Try
        'End If
        Me.Close()
    End Sub
#End Region

#Region "Datagrid TextBox Code"
    Private Sub dataGrid_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim dgcc As DataGridCell = Me.dgInventory.CurrentCell
        Dim tb As TextBox = GetEmbeddedTextBox(dgcc.ColumnNumber)
        If Not (tb Is Nothing) Then
            Dim oldValue As String = Me.dgInventory(dgcc).ToString()
            Dim newValue As String = tb.Text
            If newValue <> oldValue Then
                GetEmbeddedDGTextBox(dgcc.ColumnNumber).AddRow = Me.dgInventory.CurrentRowIndex
            End If
        End If
    End Sub
    Private Function GetEmbeddedTextBox(ByVal col As Integer) As TextBox
        Dim tbc As DataGridTextBoxColumn = Me.dgInventory.TableStyles(sTableName).GridColumnStyles(col)
        If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
            Return tbc.TextBox
        End If
        Return Nothing
    End Function
    Private Function GetEmbeddedDGTextBox(ByVal col As Integer) As DGColorTextBox
        Dim tbc As DGColorTextBox = Me.dgInventory.TableStyles(sTableName).GridColumnStyles(col)
        If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
            Return tbc
        End If
        Return Nothing
    End Function
#End Region

#Region "Datagrid Mouse Events"
    Private Sub dgInventory_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgInventory.MouseUp
        Try
            txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
            txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
            'bHit id used for skipping over the read only columns
            If bHit = False Then
                GetCellValue(sender, e)       'Go get cell values
                grdColStyle2.GetScollBar()
            End If
        Catch ex As InvalidCastException
            'Skip DBNULL
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try
    End Sub
    Private Sub Dg_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles dgInventory.MouseDown
        Dim selectedCell As System.Windows.Forms.DataGridCell
        selectedCell = Me.dgInventory.CurrentCell
        Dim myGrid As DataGrid = CType(sender, DataGrid)
        hti = myGrid.HitTest(e.X, e.Y)
        Try
            Select Case hti.Type
                Case System.Windows.Forms.DataGrid.HitTestType.None
                    Console.WriteLine("You clicked the background.")
                Case System.Windows.Forms.DataGrid.HitTestType.Cell
                    cmdUpdate.Enabled = True
                    cmdAdd.Enabled = True
                    cmdDelete.Enabled = True
                    If hti.Column = 0 Or hti.Column = 3 Then bHit = True Else bHit = False
                    ' MessageBox.Show("You clicked cell at row " & hti.Row & ", col " & hti.Column)
                Case System.Windows.Forms.DataGrid.HitTestType.ColumnHeader
                    Console.WriteLine("You clicked the column header for column " & hti.Column)
                Case System.Windows.Forms.DataGrid.HitTestType.RowHeader
                    Console.WriteLine("You clicked the row header for row " & hti.Row)
                Case System.Windows.Forms.DataGrid.HitTestType.ColumnResize
                    Console.WriteLine("You clicked the column resizer for column " & hti.Column)
                Case System.Windows.Forms.DataGrid.HitTestType.RowResize
                    Console.WriteLine("You clicked the row resizer for row " & hti.Row)
                Case System.Windows.Forms.DataGrid.HitTestType.Caption
                    Console.WriteLine("You clicked the caption")
                Case System.Windows.Forms.DataGrid.HitTestType.ParentRows
                    Console.WriteLine("You clicked the parent row")
        End Select
        Catch ex As InvalidCastException
            'Skip DBNULL
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "Error - In Mouse Down")
        End Try
    End Sub
    Private Sub dgInventory_MouseMove(ByVal sender As System.Object, ByVal e As MouseEventArgs) Handles dgInventory.MouseMove
        Dim sName As String
        Dim sUnits As String
        Dim str As String
        Try
            hti = dgInventory.HitTest(e.X, e.Y)
            Select Case hti.Type
                Case System.Windows.Forms.DataGrid.HitTestType.Cell
                    sName = dgInventory.Item(hti.Row, 1)  'Column 1
                    sUnits = dgInventory.Item(hti.Row, 2) 'Column 2
                    str = "Name: " & sName & vbCr & "  Units In Stock: " & sUnits
                    ToolTip.SetToolTip(dgInventory, str)
                    RefreshRow(hti.Row)
            End Select
        Catch
        End Try
    End Sub
    Private Function GetCellValue(ByVal sender As Object, ByVal e As MouseEventArgs)
        ' Use the HitTest method to get a HitTestInfo object.
        Dim hi As DataGrid.HitTestInfo
        Dim grid As DataGrid = CType(sender, DataGrid)
        hi = grid.HitTest(e.X, e.Y)
        ' Test if the clicked area was a cell.
        If hi.Type = DataGrid.HitTestType.Cell Then
            ' If it's a cell, get the GridTable and CurrencyManager of the clicked table.        
            Dim dgt As DataGridTableStyle = grid.TableStyles(0)
            Dim myCurrencyManager As CurrencyManager = CType(Me.BindingContext(DS.Tables(dgt.MappingName)), CurrencyManager)
            ' Set the Position to the Row.
            myCurrencyManager.Position = hi.Row
            ' Get the clicked DataGridTextBoxColumn.
            Dim gridCol As DGColorTextBox = CType(dgt.GridColumnStyles(hi.Column), DGColorTextBox)
            ' Invoke the GetColumnValueAtRow.
            Return oCellValue = gridCol.GetColValueAtRow(myCurrencyManager, hi.Row)
        End If
    End Function
#End Region

#Region "Keypress and Validating"
    Private Sub txtQty_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtQty.Validating, txtDescription.Validating
        dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
        dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
    End Sub
    Private Sub txtQty_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQty.KeyPress
        Dim KeyAscii As Short = Asc(e.KeyChar)
        Select Case KeyAscii
            Case System.Windows.Forms.Keys.Back   'same as 8
                KeyAscii = 0
            Case Keys.Enter, Keys.Tab             'same as 13
                dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
                dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
                SendKeys.Send("{TAB}")
            Case 32 To 47
                e.Handled = True
            Case 48 To 57              'Numbers
            Case Else
                e.Handled = True
        End Select
    End Sub
    Private Sub txtDescription_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDescription.KeyPress
        Dim KeyAscii As Short = Asc(e.KeyChar)
        Select Case KeyAscii
            Case System.Windows.Forms.Keys.Back   'same as 8
                KeyAscii = 0
            Case Keys.Enter, Keys.Tab             'same as 13
                dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
                dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
                SendKeys.Send("{TAB}")
            Case 32 To 47
                e.Handled = True
            Case 48 To 57              'Numbers
            Case 65 To 90, 97 To 122   'Letters
            Case Else
                e.Handled = True
        End Select
    End Sub
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Const WM_KEYDOWN As Integer = &H100
        Const WM_SYSKEYDOWN As Integer = &H104

        Try
            If ((msg.Msg = WM_KEYDOWN) Or (msg.Msg = WM_SYSKEYDOWN)) Then
                Select Case (keyData)
                    Case Keys.Enter
                        SendKeys.Send("{TAB}")
                    Case Keys.F9
                        'txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
                        'txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
                        dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
                    Case Keys.Right, Keys.Left, Keys.Down, Keys.Up, Keys.Tab
                        txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
                        txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
                End Select
            End If
        Catch ex As InvalidCastException
            'Skip DBNULL
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function
#End Region

#Region "Helper Methods"
    ' Forces a repaint of given row.
    Private Sub RefreshRow(ByVal row As Integer)
        Dim rect As Rectangle = Me.dgInventory.GetCellBounds(row, 0)
        rect = New Rectangle(rect.Right, rect.Top, Me.dgInventory.Width, rect.Height)
        Me.dgInventory.Invalidate(rect)
    End Sub 'RefreshRow
    Private Sub ResetGridColor()
        grdColStyle2.ClearGridColors()
        grdColStyle3.ClearGridColors()
    End Sub
#End Region

End Class

'MODULE

Imports System.IO
Imports System.Data
Imports System.Windows.Forms
Module ModDatagrid
#Region " Global Var's"
    Public iTag As Short
    Public DS As DataSet
    Public CurRow As DataRow
    Public oCellValue As Object            'Holds the cell value
    Public g_lngCurrentRow As Long
    Public g_lngTotalRows As Long
    Public g_strAppPath As String
    Public strAppPath = Directory.GetCurrentDirectory()
    Public grdTableStyle1 As New DataGridTableStyle
    Public grdColStyle2 As New DGColorTextBox
    Public grdColStyle3 As New DGColorTextBox
    Public myDataAdapter As OleDb.OleDbDataAdapter
    Public hti As DataGrid.HitTestInfo
    Public sTableName As String = "Contacts"
    Public sDBPass As String = ""
    Public sUSERid As String = ""
#End Region
    Public Sub AccessConnection(ByVal SQL As String)
        Try
            Dim strConnectionString As String
            strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
             "Data Source=Book.mdb;" & "User ID=" & sUSERid & ";" & _
             "Jet OLEDB:Database Password=" & sDBPass
            Dim Con As New System.Data.OleDb.OleDbConnection(strConnectionString)
            myDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQL, Con)
            Con.Open()
            ' Create and fill dataset
            DS = New DataSet(sTableName)
            myDataAdapter.Fill(DS, sTableName)
            Con.Close()
        Catch Ex As Exception
            MsgBox("Exception: " & Ex.Message & "  " & Ex.ToString, MsgBoxStyle.Critical)
        End Try
    End Sub
End Module

'CLASS

Option Explicit On

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Public Class DGColorTextBox
    Inherits DataGridTextBoxColumn

    Dim _row As New System.Collections.ArrayList
    Dim bClear As Boolean = False
    Public Sub New()
        MyBase.New()
    End Sub
    Public Property AddRow() As Integer
        Get
        End Get
        Set(ByVal Value As Integer)
            _row.Add(Value)
        End Set
    End Property
    Public Sub ClearGridColors()
        _row.Clear()
        bClear = True
    End Sub
    Public Sub GetScollBar()
        Dim g As Graphics = Me.TextBox.CreateGraphics()
        Dim size As SizeF = g.MeasureString(Me.TextBox.Text, Me.TextBox.Font)
        Try
            If Me.TextBox.Text = CType(Me.TextBox.Text, Integer) Then
                Me.TextBox.ScrollBars = ScrollBars.None
            End If
        Catch ex As Exception
            If CInt(size.Width) > Me.TextBox.Width Then
                Me.TextBox.ScrollBars = ScrollBars.Vertical
                Me.TextBox.Refresh()
            Else
                Me.TextBox.ScrollBars = ScrollBars.None
            End If
        End Try
    End Sub
    Public Function GetColValueAtRow(ByVal cm As CurrencyManager, ByVal rowNum As Integer) As Object
        Return Me.GetColumnValueAtRow(cm, rowNum)
    End Function
    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
        Dim o As Object
        Try
            If _row.Contains(rowNum) Then
                '   backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
                'Blue to Green
                backBrush = New LinearGradientBrush(bounds, Color.FromArgb(120, 0, 255, 0), Color.FromArgb(120, 0, 0, 255), LinearGradientMode.BackwardDiagonal)
                ' backBrush = New SolidBrush(Color.Silver)
                foreBrush = New SolidBrush(Color.White)
            End If
            If bClear = True Then
                backBrush = New SolidBrush(Color.GhostWhite)
                foreBrush = New SolidBrush(Color.MidnightBlue)
                bClear = False
            End If
            o = Me.GetColumnValueAtRow(source, rowNum)
            If (Not (o) Is Nothing) Then
                'Use for alpha
                'Dim c As Char
                'c = CType(o, String).Substring(0, 1)
                Dim c As String
                c = CType(o, String)

                'Use for numeric
                '  o = CInt(o)
                If (o <= 10) Then
                    backBrush = New SolidBrush(Color.White)
                    foreBrush = New SolidBrush(Color.Red)
                    If _row.Contains(rowNum) Then
                        '   backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
                        'Blue to Green
                        backBrush = New LinearGradientBrush(bounds, Color.FromArgb(120, 0, 255, 0), Color.FromArgb(120, 0, 0, 255), LinearGradientMode.BackwardDiagonal)
                        ' backBrush = New SolidBrush(Color.Silver)
                        foreBrush = New SolidBrush(Color.Red)
                    End If
                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)
            g.FillRectangle(backBrush, bounds)
            Dim vText As String = CType(o, String)
            g.DrawString(vText, Me.TextBox.Font, foreBrush, New RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height))

            '  foreBrush = New SolidBrush(Color.Red)
            ' g.DrawString(vText.Substring(0, 3), Me.TextBox.Font, foreBrush, 1, 1)  'New RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height))
            'foreBrush = New SolidBrush(Color.Green)
            ' g.DrawString(vText.Substring(3), Me.TextBox.Font, foreBrush, New RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height))
        End Try
    End Sub

End Class

'CLASS 2

Imports System
Imports System.Data
Imports System.Windows.Forms
Imports System.Drawing

Public Class DGTextAlignment
    Inherits DataGridTextBoxColumn

    Private m_iSelectedRow As Integer = -1
    Private m_hTextAlign As HorizontalAlignment = HorizontalAlignment.Left
    Private m_fmtText As New StringFormat

    Public Property DataAlignment() As HorizontalAlignment
        Get
            Return m_hTextAlign
        End Get
        Set(ByVal Value As HorizontalAlignment)
            m_hTextAlign = Value
            If m_hTextAlign = HorizontalAlignment.Center Then
                m_fmtText.Alignment = StringAlignment.Center
            ElseIf m_hTextAlign = HorizontalAlignment.Right Then
                m_fmtText.Alignment = StringAlignment.Far
            Else
                m_fmtText.Alignment = StringAlignment.Near
            End If
        End Set
    End Property

    Public Sub New()

    End Sub 'New

    Protected Overloads Overrides Sub Edit(ByVal [source] As CurrencyManager, _
     ByVal rowNum As Integer, ByVal bounds As System.Drawing.Rectangle, _
     ByVal [readOnly] As Boolean, ByVal instantText As String, _
     ByVal cellIsVisible As Boolean)

        MyBase.TextBox.TextAlign = m_hTextAlign
    End Sub

    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 o As Object
        Dim str As String = Me.NullText

        'clear the cell
        g.FillRectangle(backBrush, bounds)

        'draw the value
        o = Me.GetColumnValueAtRow(source, rowNum)
        If Not o.GetType Is GetType(System.DBNull) Then
            str = Microsoft.VisualBasic.Format(o, Me.Format)
        End If
        Dim r As Rectangle = bounds

        r.Inflate(0, -1)

        g.DrawString(str, MyBase.TextBox.Font, foreBrush, RectangleF.op_Implicit(r), m_fmtText)
    End Sub
End Class
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

708 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

16 Experts available now in Live!

Get 1:1 Help Now