Currently I use the following code to highlight the search in datagridview..but the problem is, I can't highlight the selected search..the code show below, just highlight the search that I search..So, how can I highlight search the data I want and show to the 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();
}
Please anyone...help my problem...