I too was searching for a way to do that. After going to the obvious CellPainting event I've found that using the event's Graphics object did not do the trick. However, I did manage to use the Graphics object from the DataGridView.GetGraphics() method to do highlight a part of the text.
I assume you already know how to find the cell that contains the string you search.
inside the CellPainting event the first thing you want to do is paint the cell as any other cell:
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
The next thing to do is to split the cell's text to 2 parts - the part before the search text and the search text itself. you need this in order to calculate the rectangle where you want to highlight.
Then use the MeasureString method of the Graphics object to get the location of the search text within the cell. Since I'm using the Graphics object related to the grid itself, and not the Graphics object of the event, I had to calculate the location of the highlight rectangle within the grid. I've used the DataGridView.GetCellDisplayRectangle method to find the location of the cell inside the grid, and added this location of the highlight rectangle location:
CellRectangle = Cell.DataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
HighLightedRect = new Rectangle((Point)SizeBeforeHighLight, HighLightedSize);
HighLightedRect.Location = new Point(CellRectangle.Location.X + SizeBeforeHighLight.Width, CellRectangle.Location.Y + Cell.ContentBounds.Top);
From that point on it's simply using the FillRectangle and DrawString of the Graphics object:
g.FillRectangle(new SolidBrush(Color.Black), HighLightedRect);
g.DrawString(HighlighetText, dgvGrid.Font, new SolidBrush(Color.White), HighLightedRect.Location);
g.Flush();
and of course, don't forget to set the Handled property of e to true when done:
e.Handled = true;
Oh, and one last thing: You will need to invalidate the entire grid, or at least the cells that was highlighted in the previous search every time you search a new string, otherwise you will end up with a grid full of highlighted text that has nothing to do with the current search string.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…