Highlight Part of a text in a cell of datagridview

我怕爱的太早我们不能终老 提交于 2019-11-29 08:10:58

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!