winfrom中datagridview显示数据库内容,将其中的关键字描红显示
我用vs里的datagridview显示数据的查询内容,内容以表格的形式显示在datagridview中,想把第二列中的关键字描红。只描红关键字,其他的字颜色不变。哪位大仙帮忙解决一下,找了好几天了,都没有找到解决方法。我刚注册就20分,全部给了
程序代码:
//重绘单元格 public class MyDataGridView : DataGridView { public MyDataGridView() { } private string keyWord; private Color keyColor = Color.Red; public string KeyWord { get { return keyWord; } set { keyWord = value; } } public Color KeyColor { get { return keyColor; } set { keyColor = value; } } protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e) { base.OnCellPainting(e); if (e.Value != null && !string.IsNullOrEmpty(keyWord) && e.Value.ToString().Contains(keyWord)) { string cellValue = e.Value.ToString(); Rectangle cellRect = e.CellBounds; Rectangle keyRect = e.CellBounds; float fontSizeWidth = 96 / (72 / e.CellStyle.Font.Size); float fontSizeHeight = 96 / (72 / e.CellStyle.Font.Size); keyRect.X += cellValue.Substring(0, cellValue.IndexOf(keyWord)).Length * (int)fontSizeWidth; keyRect.Y += (e.CellBounds.Height - (int)fontSizeHeight) / 2; cellRect.Y = keyRect.Y; Brush foreBrush = new SolidBrush(e.CellStyle.ForeColor); Brush keyBrush = new SolidBrush(this.keyColor); 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, foreBrush, cellRect, StringFormat.GenericDefault); e.Graphics.DrawString(keyWord, this.Font, keyBrush,keyRect,StringFormat.GenericDefault); e.Handled = true; } } } //设置样式dataGridView1 为MyDataGridView类型 this.dataGridView1.KeyColor = Color.Red; this.dataGridView1.KeyWord = "工程";