*Sorry if the title is not great. I am not sure how to summarize this question into a few words.
I have a DataGridView and a search box. When the user types a query, any matching result in the DataGridView cells, is highlighted. To achieve this I use the CellPainting event of DataGridView and draw a rectangle behind the results.
Some of the cells are oriented Right-To-Left:
And some are oriented Left-To-Right:
When the orientation is RTL, I use the following formula to calculate the highlight rectangle X-coordinate:
e.CellBounds.Right - queryWidth - stringBeforeQueryWidth;
and stringBeforeQueryWidth refers to this:
When the orientation is LTR, I use the following formula:
e.CellBounds.Left + stringBeforeQueryWidth;
and stringBeforeQueryWidth refers to this:
The way I calculate stringBeforeQueryWidth is as follows:
var stringBeforeQuery = cellValue.Substring(0, cellValue.IndexOf(query));
var stringBeforeQueryWidth =
e.Graphics.MeasureString(stringBeforeQuery, font, e.CellBounds.Width, format).Width;
So when the orientation is RTL, I use the fact that all the characters that come before the query itself will be drawn to the right of it, and when the orientation is LTR, I use the fact that all the characters that come before the query itself will be drawn to the left of it.
The problem starts when the cell contains a string that combines LTR and RTL texts. For example:

Let's say the query is 13. To calculate stringBeforeQueryWidth I need the width of רחוב ישראל ישראלי and the width of /5. I cannot use cellValue.Substring(0, cellValue.IndexOf(query)) to retrieve them, like I did when there was only one orientation, because רחוב ישראל ישראלי comes before the query, and /5 comes after the query.
So how can I get the width of the part of the string that is located to the right of the query?





