This is the case: I want to search for a word in a whole DataGridView
through looping it's Row
s, and then for each match I highlight the word. The major inflexibility I face is that columns have different System.Windows.Forms.DataGridViewContentAlignment
s. So in paiting (highlighting) mathced word in cells I should take care of cell's ContentAlignment
.
So far I have written the following code to find the matches
private int FindAllMatches()
{
int itemsFound = 0;
for (int r = 0; r < dgvMain.Rows.Count; r++)
{
DataGridViewRow row = dgvMain.Rows[r];
for (int c = 0; c < Columns.Count; c++)
{
string cellValue = (dgvMain.Rows[r].Cells[c].Value ?? "").ToString();
if (cellValue.Contains(SearchValue.ToString()))
{
HighlightRow(row); // highlights whole row, weak solution
itemsFound++;
break;
}
}
}
return itemsFound;
}
But as you see I have currently managed to highlight the rows which have at least one match. What I need is a code to highlight only the portion of cell which matches my specific word (SearchValue).
I know I should use the CellPainting
Event, but I don't know how to paint the word inside a Cell
considering the Cell
's ContentAlignment