【发布时间】:2021-06-20 01:06:39
【问题描述】:
在 WinForm 上的 DataGridView 中我有:
dataGridViewAnzeige.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
dataGridViewAnzeige.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
我在 CellPainting 上绘制背景, 我的搜索执行“拆分搜索”以过滤更多结果
但是包装文本的测量失败了,有什么想法吗?
第二行的位置失败..
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex > -1 && e.ColumnIndex > -1 && dataGridView1.Columns[e.ColumnIndex].Name != "Id")
{
var suchtext = searchStringTextBox.Split(null);
List<Rectangle> rectangleList = new List<Rectangle>();
// Check data for search
if (!String.IsNullOrWhiteSpace(searchStringTextBox.Trim()))
{
foreach (var txtSuche in suchtext)
{
String gridCellValue = e.FormattedValue.ToString();
// check the index of search text into grid cell.
int startIndexInCellValue = gridCellValue.ToLower().IndexOf(txtSuche.Trim().ToLower());
// IF search text is exists inside grid cell then startIndexInCellValue value will be greater then 0 or equal to 0
if (startIndexInCellValue >= 0)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
//the highlite rectangle
Rectangle hl_rect = new Rectangle();
hl_rect.Y = e.CellBounds.Y + 2;
//find the size of the text before the search word in grid cell data.
String sBeforeSearchword = gridCellValue.Substring(0, startIndexInCellValue);
//size of the search word in the grid cell data
String sSearchWord = gridCellValue.Substring(startIndexInCellValue, txtSuche.Trim().Length);
Size s1 = TextRenderer.MeasureText(e.Graphics, sBeforeSearchword, e.CellStyle.Font, e.CellBounds.Size, TextFormatFlags.TextBoxControl);
Size s2 = TextRenderer.MeasureText(e.Graphics, sSearchWord, e.CellStyle.Font, e.CellBounds.Size, TextFormatFlags.TextBoxControl);
if (s1.Width > 5)
{
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;
}
//fail on textalign in middle
hl_rect.Height = s2.Height;
rectangleList.Add(hl_rect);
}
}
}
//color for showing highlighted text in grid cell
SolidBrush hl_brush;
hl_brush = new SolidBrush(Color.Yellow);
//paint the background behind the search word
foreach(var recto in rectangleList)
{
e.Graphics.FillRectangle(hl_brush, recto);
}
hl_brush.Dispose();
e.PaintContent(e.CellBounds);
}
}
我在 CellPainting 上绘制背景,我的搜索执行“拆分搜索”以过滤更多结果
但是包装文本的测量失败了,有什么想法吗?
第二行的位置失败..
【问题讨论】:
标签: c# datagridview highlight