Graphics.FillRectangle
не изменит ForeColor. Я изменил тогда событие CellPainting
. Я использую Graphics.DrawString
для изменения ForeColor.
if ((e.RowIndex <= -1 ? false : e.ColumnIndex > -1))
{
string str = txtSearch.Text.Trim();
if (!string.IsNullOrWhiteSpace(str))
{
string[] strArrays = str.Split(new char[] { ' ' });
string[] strArrays1 = strArrays;
for (int i = 0; i < (int)strArrays1.Length; i++)
{
string str1 = strArrays1[i];
string str2 = e.FormattedValue.ToString();
int num = str2.ToLower().IndexOf(str1.ToLower());
if (num >= 0)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
Size size = TextRenderer.MeasureText(e.Graphics, str2, e.CellStyle.Font, e.CellBounds.Size);
Size searchSize = TextRenderer.MeasureText(e.Graphics, str1, e.CellStyle.Font, e.CellBounds.Size);
List<int> indexes = str2.AllIndexesOf(str1).ToList<int>();
string leadingPart = string.Empty;
string printString = string.Empty;
for (int index = 0; index < str2.Length; index++)
{
if (indexes.Contains(index))//Search string starts here
{
leadingPart = str2.Substring(0, index);//leading part of the string
Size leadingSize = TextRenderer.MeasureText(e.Graphics, leadingPart, e.CellStyle.Font, e.CellBounds.Size);
Rectangle rect = new Rectangle(new Point(e.CellBounds.X + leadingSize.Width, e.CellBounds.Y + 4), searchSize);
SolidBrush brush = new SolidBrush(Color.Green);
e.Graphics.DrawString(str1, e.CellStyle.Font, brush, rect);
brush.Dispose();
index += str1.Length - 1;
}
else
{
int nextIndex = indexes.FirstOrDefault(x => x > index);
leadingPart = str2.Substring(0, index);
printString = index < nextIndex ? str2.Substring(index, nextIndex - index) : str2.Substring(index);
Size leadingSize = TextRenderer.MeasureText(e.Graphics, leadingPart, e.CellStyle.Font, e.CellBounds.Size);
Size printSize = TextRenderer.MeasureText(e.Graphics, printString, e.CellStyle.Font, e.CellBounds.Size);
Rectangle rect;
if (index > 0)
rect = new Rectangle(new Point(e.CellBounds.X + leadingSize.Width, e.CellBounds.Y + 4), printSize);//4 is for adjusting the text top position
else
rect = new Rectangle(new Point(e.CellBounds.X, e.CellBounds.Y + 4), printSize);
SolidBrush brush = new SolidBrush(Color.Black);
e.Graphics.DrawString(printString, e.CellStyle.Font, brush, rect);
brush.Dispose();
index += printString.Length - 1;
}
}
}
}
}
}
Обратите внимание, что AllIndexesOf
является расширением метод для нахождения всех вхождений определенной строки в заданной длинной строке, которую я получил из этого поста .
public static IEnumerable<int> AllIndexesOf(this string sourceString, string subString)
{
return Regex.Matches(sourceString, subString,RegexOptions.IgnoreCase).Cast<Match>().Select(m => m.Index);
}
Надеюсь, это поможет.