how to change color select part of text in datagridview cell by click button ? RRS feed

  • Question

  • I want select part of text in row and click button change color part text to (red or green ........) and save change color part text

    Monday, March 27, 2017 8:02 PM

All replies

  • Hi

    A DataGridView doesn't support partial text color in a cell - only all of the text can be changed.

    Regards Les, Livingston, Scotland

    Monday, March 27, 2017 8:08 PM
  • The following DataGridView column was done in C# but can be used in VB.NET that works with RichText.

    I downloaded the source and tinkered a little e.g.

    It's not easy no matter the language as you will need to manipulate cell data, parse and format with RTF raw codes.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, March 27, 2017 11:46 PM
  • Hi srajmuneer,
    It seems that you could not change the text color that you select in the datagridview cell by click button, but you can use DataGridView1_CellPainting event to change the color.

    Dim mdtbColourMap As DataTable = Nothing
    Private Sub Form14_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            With DataGridView1
                .Columns.Add("Column1", "Column1")
                .Columns.Add("Column2", "Column2")
                .Columns.Add("Column3", "Column3")
                .Rows.Add("Welcome to_ the", "Wonderful-", "World of computing_")
                .Rows.Add("This_ is what+ I", "Want-", "In My_ laptop")
                .Rows.Add("X_is always+", "Greater-", "Than_ y")
                .Columns(0).Width = 120
                .Columns(1).Width = 120
                .Columns(2).Width = 120
            End With
            '----Above should be replaced with your data access
            'Define the search terms and color for each
            mdtbColourMap = New DataTable
            mdtbColourMap.Columns.Add(New DataColumn("SearchTerm", GetType(String)))
            mdtbColourMap.Columns.Add(New DataColumn("TextColor", GetType(Brush)))
            mdtbColourMap.Rows.Add("_", Drawing.Brushes.Green)
            mdtbColourMap.Rows.Add("+", Drawing.Brushes.Red)
            mdtbColourMap.Rows.Add("-", Drawing.Brushes.Purple)
    End Sub
    Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
            If e.ColumnIndex >= 0 And e.RowIndex >= 0 Then
                Dim newRect As New Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1,
              e.CellBounds.Width - 4, e.CellBounds.Height - 4)
                Dim backColorBrush As New SolidBrush(e.CellStyle.BackColor)
                Dim gridBrush As New SolidBrush(Me.DataGridView1.GridColor)
                Dim gridLinePen As New Pen(gridBrush)
                    ' Erase the cell.
                    e.Graphics.FillRectangle(backColorBrush, e.CellBounds)
                    ' Draw the grid lines (only the right and bottom lines; 
                    ' DataGridView takes care of the others).
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                e.CellBounds.Bottom - 1)
                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                e.CellBounds.Top, e.CellBounds.Right - 1,
                    ' Draw the inset highlight box.
                    e.Graphics.DrawRectangle(Pens.Blue, newRect)
                    ' Draw the text content of the cell, ignoring alignment. 
                    If (e.Value IsNot Nothing) Then
                        Dim strValue As String = CStr(e.Value)
                        Dim strWords() As String = Split(strValue, " ")
                        Dim strAlignment As String = "LEFT"
                        If e.ColumnIndex = 0 Then strAlignment = "RIGHT"
                        Dim sngX As Integer
                        If strAlignment = "LEFT" Then
                            sngX = e.CellBounds.X + 2
                            sngX = e.CellBounds.Right - 4 - e.Graphics.MeasureString(strValue, e.CellStyle.Font).Width
                        End If
                        For i As Integer = 0 To strWords.GetUpperBound(0)
                            Dim brsTextColor As Drawing.Brush = Nothing
                            For j As Integer = 0 To mdtbColourMap.Rows.Count - 1
                                Dim strSearchTerm As String = mdtbColourMap.Rows(j).Item("SearchTerm").ToString
                                If InStr(strWords(i), strSearchTerm) > 0 Then
                                    brsTextColor = DirectCast(mdtbColourMap.Rows(j).Item("TextColor"), Drawing.Brush) 'change the color
                                    Exit For
                                End If
                            Next j
                            If brsTextColor Is Nothing Then
                                brsTextColor = Brushes.Black 'default
                            End If
                            e.Graphics.DrawString(strWords(i), e.CellStyle.Font, brsTextColor, sngX, e.CellBounds.Y + 2, StringFormat.GenericDefault)
                            sngX += e.Graphics.MeasureString(strWords(i), e.CellStyle.Font).Width
                        Next i
                    End If
                    e.Handled = True
                End Try
            End If
        End Sub

    More detailed info, please refer to DataGridView.CellPainting event.

    Best Regards,
    Cherry Bu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Tuesday, March 28, 2017 8:35 AM
  • thank you Cherry Bu how to change color collection for text in datagridview use connection sql server in your code
    Tuesday, March 28, 2017 3:38 PM
  • thanks Kareninstructor , I'm sorry I'm try with your address and convert c# to but not work

    thanks for answer , but I want change color or highlight to string , help code :

    I'm try with my code but not work 

    Option Strict On
    Option Explicit On
    Option Infer Off
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Drawing
    Imports System.Text
    Imports System.Windows.Forms
    Imports System.IO
    Partial Public Class Form1
        Inherits Form
        'Private _table As New DataTable()
        ' Create new DataTable and DataSource objects.
        Private _table As New DataTable()
        Private Sub btnHighlight_Click(sender As Object, e As EventArgs) Handles btnHighlight.Click
            For Each row As DataRow In _table.Rows
                SetTextBoldByColumn(row, "col1", Me.txtSearch.Text)
                SetTextBoldByColumn(row, "col2", Me.txtSearch.Text)
        End Sub
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            _table.Rows.Add("First Row Cell2", "First Row Cell1 ")
            _table.Rows.Add("Second Row Cell2", "Second Row Cell1 ")
            Me.dataGridView1.DataSource = _table
        End Sub
        Private Sub SetTextBoldByColumn(row As DataRow, colName As String, boldText As String)
            Dim plainText As String
            If row.HasVersion(DataRowVersion.Original) Then
                plainText = row(colName, DataRowVersion.Original).ToString()
                plainText = row(colName).ToString()
            End If
            row(colName) = GetRtf(plainText, Me.txtSearch.Text)
        End Sub
        Public Function GetRtf(originalText As String, boldText As String) As String
            If String.IsNullOrEmpty(boldText) Then
                Return originalText
            End If
            Dim rtf As String = "{\rtf " + originalText.Replace(boldText, (Convert.ToString("\b ") & boldText) + "\b0 ") + "}"
            Return rtf
        End Function
        'Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
        '    Dim f As New OpenFileDialog()
        '    f.Filter = "RTF file(*.rtf)|*.rtf"
        '    If f.ShowDialog() = DialogResult.OK Then
        '        Me.richTextBox1.LoadFile(f.FileName)
        '    End If
        'End Sub
        'Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
        '    If Me.dataGridView1.CurrentCell IsNot Nothing Then
        '        'this.dataGridView1.CurrentCell.Value = this.richTextBox1.Rtf;
        '        Me.dataGridView1.Rows(0).Cells(1).Value = Me.richTextBox1.Rtf
        '    End If
        'End Sub
    End Class

    Saturday, April 1, 2017 7:34 PM
  • Hi

    I don't know if this is of any help, but, here it is anyway.

    Needs a DGV a TextBox1 and Button1

    This example will search all the cells in a datagridview and if the contents CONTAIN the text in the textbox then willhighlight/embolden - if not a match, will reset to default.

    Option Strict On
    Option Explicit On
    Option Infer Off
    Public Class Form1
        Private _table As New DataTable()
        ' set up colours and fontsfor Default and HighLight cells
        Dim defFont As New Font("Arial", 10, FontStyle.Regular)
        Dim highFont As New Font("Arial", 12, FontStyle.Bold)
        Dim defColor As Color = Color.White
        Dim highColor As Color = Color.Pink
        Private Sub Form1_Load(sender As System.Object, e As EventArgs) Handles MyBase.Load
            _table.Rows.Add("First Row Cell2", "First Row Cell1 ")
            _table.Rows.Add("Second Row Cell2", "Second Row Cell1 ")
            Me.DataGridView1.DataSource = _table
            DataGridView1.DefaultCellStyle.BackColor = defColor
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            ' this button click will:
            'look through all the cells and if any of them
            ' CONTAIN the text in the TextBox then will highlight
            ' and embolden them - otherwise reset to defaults.
            If Trim(TextBox1.Text).Length < 1 Then Exit Sub
            For Each r As DataGridViewRow In DataGridView1.Rows
                If Not r.Index = DataGridView1.NewRowIndex Then
                    For Each c As DataGridViewCell In r.Cells
                        If Trim(c.Value.ToString.ToLower).Contains(Trim(TextBox1.Text.ToLower)) Then
                            c.Style.Font = highFont
                            c.Style.BackColor = highColor
                            c.Style.Font = defFont
                            c.Style.BackColor = defColor
                        End If
                End If
        End Sub
    End Class


    Regards Les, Livingston, Scotland

    Saturday, April 1, 2017 7:42 PM
  • thank you Cherry Bu,your code how to use click button and take value to change color in textbox

    example :

    first to view datagridview the data normal

    when write into textbox1. text = 'army , or , take , work' (search for any text to change color green)

    and click button change color

    Monday, April 3, 2017 3:15 PM