How can i Highlight Part of a text in a cell of datagridview ?
I am using C#.
For example user searches book. on of cells contains bookmark. I want to highlight "book" in bookmark.
Thanks.
Edition. Is this code ok?
Private Sub DataGridView1_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then
e.Handled = True
e.PaintBackground(e.CellBounds, True)
Dim sw As String = GetSearchWord(e.ColumnIndex)
If Not String.IsNullOrEmpty(sw) Then
Dim val As String = DirectCast(e.FormattedValue, String)
Dim sindx As Integer = val.ToLower.IndexOf(sw.ToLower)
If sindx >= 0 Then
'the highlite rectangle
Dim hl_rect As New Rectangle()
hl_rect.Y = e.CellBounds.Y + 2
hl_rect.Height = e.CellBounds.Height - 5
'find the size of the text before the search word
'and the size of the search word
Dim sBefore As String = val.Substring(0, sindx)
Dim sWord As String = val.Substring(sindx, sw.Length)
Dim s1 As Size = TextRenderer.MeasureText(e.Graphics, sBefore, e.CellStyle.Font, e.CellBounds.Size)
Dim s2 As Size = TextRenderer.MeasureText(e.Graphics, sWord, e.CellStyle.Font, e.CellBounds.Size)
'adjust the widths to make the highlite more accurate
If s1.Width > 5 Then
hl_rect.X = e.CellBounds.X + s1.Width - 5
hl_rect.Width = s2.Width - 6
Else
hl_rect.X = e.CellBounds.X + 2
hl_rect.Width = s2.Width - 6
End If
'use darker highlight when the row is selected
Dim hl_brush As SolidBrush
If ((e.State And DataGridViewElementStates.Selected) <> DataGridViewElementStates.None) Then
hl_brush = New SolidBrush(Color.DarkGoldenrod)
Else
hl_brush = New SolidBrush(Color.LightGoldenrodYellow)
End If
'paint the background behind the search word
e.Graphics.FillRectangle(hl_brush, hl_rect)
hl_brush.Dispose()
End If
End If
'paint the content as usual
e.PaintContent(e.CellBounds)
End If
End Sub
I don't think there's any built in way of doing it, but I'd assume that you could handle the CellPainting
event of the DataGridView
, set e.Handled = true;
and then draw it yourself as you need it.
You might be able to use PaintBackground
to minimize the amount of work you have to do yourself.