如何突出显示DataGridView中的搜索文本?
问题描述:
我想突出显示DataGridView
中的给定搜索文本。我已经尝试过cellFormatting事件以找到searchtext
的边界并绘制FillRectangle
,但我无法准确获得搜索文本的边界。如何突出显示DataGridView中的搜索文本?
在添加图像,我试图突出显示文本“O”,但它凸显其他角色也。
任何人都可以与我分享如何绘制完美的矩形来突出显示搜索到的文本。
Regards, Amal Raj。
答
您需要使用CellPainiting事件。试试这个代码:
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();
}
+0
解决方案正常工作。但是当我们设置了WrapMode时,上面的格式会禁用wrapmode。突出显示在包装模式下不起作用。 – Amal
+0
这个工作,但是,对我来说,单元格的字体/布局/对齐方式与其他单元格完全不同,所以我必须仔细研究一下。 –
发表你的代码到目前为止你已经尝试过。请参阅http://stackoverflow.com/questions/22322675/how-to-highlight-search-results-in-gridview-using-asp-net –
我要求WinForms技术。 – Amal
你必须执行,当您在结合网格法的数据,你可以找到这个东西(http://stackoverflow.com/questions/10090691/add-progress-bar-in-gridview-using-datatable-or-一定条件dataset-in-window-application/10100992#10100992) –