如何在datagridview中显示突出显示搜索

时间:2016-06-01 01:53:10

标签: c# datagridview c#-3.0 advanceddatagrid

目前我使用以下代码突出显示datagridview中的搜索..但问题是,我无法突出显示所选搜索..下面的代码显示,只是突出显示我搜索的搜索..所以,怎么能我突出显示搜索我想要的数据并显示到datagridview。

    private void dataGridView2_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.RowIndex >= 0 & e.ColumnIndex >= 0 & IsSelected)
        {
            e.Handled = true;
            e.PaintBackground(e.CellBounds, true);

            string sw = textBox2.Text;

            if (!string.IsNullOrEmpty(sw))
            {
                string val = (string)e.FormattedValue;
                int sindx = val.ToLower().IndexOf(sw.ToLower());
                int sCount = 1;
                while (sindx >= 0)
                //if (sindx >= 0)
                {
                    Rectangle hl_rect = new Rectangle();
                    hl_rect.Y = e.CellBounds.Y + 2;
                    hl_rect.Height = e.CellBounds.Height - 5;

                    string sBefore = val.Substring(0, sindx);
                    string sWord = val.Substring(sindx, sw.Length);
                    Size s1 = TextRenderer.MeasureText(e.Graphics, sBefore, e.CellStyle.Font, e.CellBounds.Size);
                    Size s2 = TextRenderer.MeasureText(e.Graphics, sWord, e.CellStyle.Font, e.CellBounds.Size);

                    if (s1.Width > 5)
                    {
                        hl_rect.X = e.CellBounds.X + s1.Width - 5;
                        hl_rect.Width = s2.Width - 6;
                    }
                    else
                    {
                        hl_rect.X = e.CellBounds.X + 2;
                        hl_rect.Width = s2.Width - 6;
                    }

                    SolidBrush hl_brush = default(SolidBrush);
                    if (((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.None))
                    {
                        hl_brush = new SolidBrush(Color.DarkGoldenrod);
                    }
                    else
                    {
                        hl_brush = new SolidBrush(Color.Yellow);
                    }

                    e.Graphics.FillRectangle(hl_brush, hl_rect);

                    hl_brush.Dispose();
                    sindx = val.ToLower().IndexOf(sw.ToLower(), sCount++);
                }
            }

            e.PaintContent(e.CellBounds);
        }
    }


    bool IsSelected = false;
    private void SearchStringPosition(string Searchstring)
    {
        IsSelected = true;

    }



    private void btnFind_Click(object sender, EventArgs e)
    {

        SearchStringPosition(textBox2.Text);
        dataGridView2.Refresh();

    }

请任何人......帮我解决问题...

0 个答案:

没有答案