对于这个问题的引用,在datagridview中突出显示搜索,解决方案有效,但它在整个数据视图中的搜索字符串很大。
我的问题是,是否有可能在特定栏目中高亮搜索文本?
以下是解决方案中的代码副本:
string keyValue = "Co"; //search text
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.Value == null) return;
StringFormat sf = StringFormat.GenericTypographic;
sf.FormatFlags = sf.FormatFlags | StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.DisplayFormatControl;
e.PaintBackground(e.CellBounds, true);
SolidBrush br = new SolidBrush(Color.White);
if (((int)e.State & (int)DataGridViewElementStates.Selected) == 0)
br.Color = Color.Black;
string text = e.Value.ToString();
SizeF textSize = e.Graphics.MeasureString(text, Font, e.CellBounds.Width, sf);
int keyPos = text.IndexOf(keyValue, StringComparison.OrdinalIgnoreCase);
if (keyPos >= 0)
{
SizeF textMetricSize = new SizeF(0, 0);
if (keyPos >= 1)
{
string textMetric = text.Substring(0, keyPos);
textMetricSize = e.Graphics.MeasureString(textMetric, Font, e.CellBounds.Width, sf);
}
SizeF keySize = e.Graphics.MeasureString(text.Substring(keyPos, keyValue.Length), Font, e.CellBounds.Width, sf);
float left = e.CellBounds.Left + (keyPos <= 0 ? 0 : textMetricSize.Width) + 2;
RectangleF keyRect = new RectangleF(left, e.CellBounds.Top + 1, keySize.Width, e.CellBounds.Height - 2);
var fillBrush = new SolidBrush(Color.Yellow);
e.Graphics.FillRectangle(fillBrush, keyRect);
fillBrush.Dispose();
}
e.Graphics.DrawString(text, Font, br, new PointF(e.CellBounds.Left + 2, e.CellBounds.Top + (e.CellBounds.Height - textSize.Height) / 2), sf);
e.Handled = true;
br.Dispose();
}发布于 2018-04-20 06:38:14
通常,当所有者绘制Control时,整个区域都会使用Paint事件.
DataGridView.CellPainting事件是不同的;它分别为DGV 中的每个(可见的) Cell调用。
这意味着,只需检查它将要绘制的单元格,就可以完全区分某些Cells、Rows或Columns。
DataGridViewCellPaintingEventArgs包括e.ColumnIndex和e.RowIndex。您可以通过测试某个列名来解决问题,如下所示:
if (dataGridView1.Columns[e.ColumnIndex].Name != "name") return;还可以测试要包含或排除的列列表:
var names = new List<string> {"firstname", "lastname"};
string colName = dataGridView1.Columns[e.ColumnIndex].Name;
if (names.Contains(colName)) return;或者像这样破解它:
string names = " firstname lastname ";
string colName = dataGridView1.Columns[e.ColumnIndex].Name;
if (names.Contains(" " + colName + " ")) return;Rows没有Names,所以您需要检查它们的索引。注意,行标题列和列标题行都有-1作为索引,可以像其他单元格一样绘制和跳过。
有关油漆DGV的其他值得注意的详细信息可以在DataGridViewCellPaintingEventArgs、PaintParts、RowPrePaint、RowPostPaint上的MSDN上找到。
https://stackoverflow.com/questions/49921034
复制相似问题