How to highlight search text in DataGridView?

北战南征 提交于 2020-01-06 03:48:06

问题


I want to highlight the given search text in the DataGridView. I have tried cellFormatting event to find the bounds of the searchtext and draw FillRectangle, but i could not exactly get the bounds of the search text.

In the added image, i have tried to highlight text "o" but it highlights other characters also.

Could anyone share me how to draw perfect rectangle to highlight the searched text.

Regards, Amal Raj.


回答1:


You need to use the CellPainiting event. Try this code:

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();
    }


来源:https://stackoverflow.com/questions/38788746/how-to-highlight-search-text-in-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!