希望在dataGridView的单元格内对我要查找的关键字及其单元格背景进行重绘,以便查看时可以快速定位,现在背景和文字重绘已经做到了,但关键字高亮显示有问题,横向定位不准,请求支援?
关键代码如下:
private void dgvListItems_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.Value != null && !string.IsNullOrEmpty(txtSearchKey.Text) && e.Value.ToString().ToUpper().Contains(txtSearchKey.Text.ToUpper())) { using (Brush foreColorBrush = new SolidBrush(e.CellStyle.ForeColor), keywordColorBrush = new SolidBrush(Color.DodgerBlue)) { var cellText = e.Value.ToString(); var searchKey = txtSearchKey.Text; // 绘制背景 e.PaintBackground(e.ClipBounds, false); //绘制自定义背景 var bounds = e.CellBounds; bounds.Inflate(new Size(-1, -1)); e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), bounds); // 绘制背景(被选中时) if (e.State == (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed | DataGridViewElementStates.Visible)) e.PaintBackground(e.ClipBounds, true); // 绘制原文本 e.Graphics.DrawString(cellText, e.CellStyle.Font, foreColorBrush, e.CellBounds, StringFormat.GenericDefault); //获取关键字之前的文字 var searchKeyIndex = cellText.ToUpper().IndexOf(searchKey.ToUpper()); var textBeforeSearchKey = cellText.Substring(0,searchKeyIndex); //获取高亮关键字之前的文字的长度 var searchKeyIndentSize = e.Graphics.MeasureString(textBeforeSearchKey, e.CellStyle.Font); var searchKeyCellBounds = new RectangleF(e.CellBounds.Location, e.CellBounds.Size); searchKeyCellBounds.X += searchKeyIndentSize.Width; // 在原文本上绘制红色关键字 e.Graphics.DrawString(searchKey, e.CellStyle.Font, keywordColorBrush, searchKeyCellBounds, StringFormat.GenericDefault); // 已完成事件处理,继续本身处理 e.Handled = true; } } }
已经解决了!