...

When developing a web page, we might have strings which are too long to fit in a fixed width cell of a table or Grid. The problem is more common when working with text in a nested grid. This might also occur when a web page is localized especially when dealing with languages that have longer text.

Typically the requirement is that the text should fit within a single line and should not get wrapped to the next line in the cell (for any language or culture). Because the screen length of the text can vary from language to language, it’s not straightforward to fix the limit of truncation. Below is an explanation of how it can be achieved along with code snippets.

The function Truncate Text takes the following parameters as input:

• Any text (any language as per the browser culture settings)
• Maximum width of the cell to fit the given text in
• Font name
• Font size
• Boolean value if the font is Bold

Returns a string with the ellipses (…) at the end by truncating the rest of the string.

The TruncateText function uses a custom function GetCharWidth which takes in a specific character with the font details as input and returns the width of that character.

The width of each character in the text provided as input is measured, summed up and compared to the maximum width allowed in the cell. The index of the character from which the text need to be truncated is captured and the substring of that text is taken till that index.

The computation of the length of the string and the maximum width specified is calculated and the string is truncated to fit the cell width specified.

Now we have the string/link to fit the grid cell width specified.