我想在DataGridView中突出显示给定的搜索文本。我已经尝试了cellFormatting事件来找到searchtext的界限并绘制FillRectangle,但是我无法完全获得搜索文本的界限。

c# - 如何在DataGridView中突出显示搜索文本?-LMLPHP

在添加的图像中,我尝试突出显示文本“ o”,但同时也突出显示其他字符。

谁能告诉我如何绘制完美的矩形以突出显示搜索到的文本。

问候,
阿玛尔·拉杰(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();
    }

关于c# - 如何在DataGridView中突出显示搜索文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38788746/

10-12 00:27
查看更多