【问题标题】:How to highlight search text in DataGridView?如何突出显示 DataGridView 中的搜索文本?
【发布时间】:2016-08-05 12:00:05
【问题描述】:

我想在DataGridView 中突出显示给定的搜索文本。我已经尝试通过 cellFormatting 事件来查找 searchtext 的边界并绘制 FillRectangle,但我无法准确获取搜索文本的边界。

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

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

问候, 阿迈勒·拉吉。

【问题讨论】:

标签: c# winforms datagridview highlighting


【解决方案1】:

您需要使用 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();
    }

【讨论】:

  • 解决方案工作正常。但是当我们设置了 WrapMode 时,上面的格式会禁用 wrapmode。并且突出显示在包装模式下不起作用。
  • 这行得通,但是,对我来说,单元格的字体/布局/对齐方式与其他单元格完全不同,因此我必须对此进行更多研究。
  • 带包装字的解决方案stackoverflow.com/questions/66762116/…
猜你喜欢
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 2012-06-25
相关资源
最近更新 更多