怎么实现多关键字 呢
关键字中间用 ; 隔开
分割后循环 肯定也行,不过会不会 效率很差呢
关键字中间用 ; 隔开
分割后循环 肯定也行,不过会不会 效率很差呢
程序代码:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
namespace Winform中DataGridView单元格内容字体突出显示
{
class MyDataGridView : DataGridView
{
public MyDataGridView()
{
}
public Color KeyColor { get; set; }
public string KeyWord { get; set; }
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
base.OnCellPainting(e);
if (e.Value != null)
{
string cellValue = e.Value.ToString();//单元格原本内容
Rectangle cellRect = e.CellBounds;//默认单元格
float fontSizeWidth = 96 / (72 / e.CellStyle.Font.Size);
float fontSizeHeight = 96 / (72 / e.CellStyle.Font.Size);
//用一个list来保存关键字及对应的区域
List<KeyValuePair<string, Rectangle>> cc = new List<KeyValuePair<string, Rectangle>>();
//分解关键字;隔开的
string[] al = this.KeyWord.Split(';');
foreach (string i in al)
{
if (cellValue.Contains(i))
{
Rectangle ee = e.CellBounds; //单元格内容区域,默认定义为单元格大小
//关键字的坐标
ee.X += cellValue.Substring(0, cellValue.IndexOf(i)).Length * (int)fontSizeWidth; //关键字左下角点坐标
ee.Y += (e.CellBounds.Height - (int)fontSizeHeight) / 2;//关键字右上角点坐标
cc.Add(new KeyValuePair<string, Rectangle>(i, ee));//收集到所有关键字的区域
}
}
if (cc.Count > 0)
{
//原文本的Y坐标
cellRect.Y = cc[0].Value.Y;//这一句有bug,对自动换行的有问题
//绘制背景色
e.PaintBackground(e.ClipBounds, false);
//绘制背景色(被选中状态下)
if (e.State == (DataGridViewElementStates.Displayed | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible))
{
e.PaintBackground(e.ClipBounds, true);
}
//分别绘制原文本和现在改变颜色的文本
e.Graphics.DrawString(cellValue, this.Font, new SolidBrush(e.CellStyle.ForeColor), cellRect, StringFormat.GenericDefault);
cc.ForEach(p =>
{
e.Graphics.DrawString(p.Key, this.Font, new SolidBrush(this.KeyColor), p.Value, StringFormat.GenericDefault);
});
//提交事务
e.Handled = true;
}
}
}
}
}