
A helpful feature in MS Word is AutoFit, which adapts a table width to the current content. This sample shows how to realize this with TX Text Control .NET.
Two functions are required to retrieve the content of every cell and to resize the table afterwards. The first function checkCellWidth loops through all cells in the current table. Every column of the table should be as wide as the longest line in a cell. Therefore, we check the line length of every line in every cell of the current table. We use the Line collection to retrieve the bounds of the text.
The longest line of every cell in a complete column will be stored in an array which holds every new width for all columns in the table.
Private Sub checkCellWidth()
Dim colWidths(TextControl1.Tables.GetItem().Columns.Count - 1) As Integer
For Each tc As TXTextControl.TableCell In TextControl1.Tables.GetItem().Cells
Dim textBounds As Integer = 0
For i As Integer = tc.Start To tc.Start + tc.Length - 1
If TextControl1.Lines.GetItem(i).TextBounds.Width > textBounds Then
textBounds = TextControl1.Lines.GetItem(i).TextBounds.Width
End If
Next
If textBounds > colWidths.GetValue(tc.Column - 1) Then
colWidths.SetValue(textBounds, tc.Column - 1)
End If
Next
End SubAfter that, we have to adjust the table column according to the stored values in the array.
Private Sub resizeTable(ByVal colSize() As Integer, ByVal table As TXTextControl.Table)
Dim i As Integer
Dim a As Integer
For a = 1 To table.Columns.Count
If colSize.GetValue(i) = 0 Then
Else
table.Columns.GetItem(a).Width = colSize.GetValue(i) + 200
End If
i += 1
Next
End SubThe minimum requirements for this sample application are TX Text Control .NET trial version and Visual Studio .NET 2003.