Skype:TextControlSupport
Orders:877-462-4772
TX Text Control - word processing components.
What is this?Syndicate this content

Building a Table AutoFit Feature

This source code snippet requires TX Text Control .NET
Author:TX Text Control Support Department
Language:Visual Basic .NET
Version:1.0
Released:June 21, 2005
Last modified:January 11, 2008
Requirements:TX Text Control .NET with Visual Basic .NET
Download code:tx_samples_dotnet_autofit.zip Download [20.77 KB, ZIP]
Click to enlarge

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.

  1. Private Sub checkCellWidth()
  2. Dim colWidths(TextControl1.Tables.GetItem().Columns.Count - 1) As Integer
  3.  
  4. For Each tc As TXTextControl.TableCell In TextControl1.Tables.GetItem().Cells
  5. Dim textBounds As Integer = 0
  6.  
  7. For i As Integer = tc.Start To tc.Start + tc.Length - 1
  8. If TextControl1.Lines.GetItem(i).TextBounds.Width > textBounds Then
  9. textBounds = TextControl1.Lines.GetItem(i).TextBounds.Width
  10. End If
  11. Next
  12.  
  13. If textBounds > colWidths.GetValue(tc.Column - 1) Then
  14. colWidths.SetValue(textBounds, tc.Column - 1)
  15. End If
  16. Next
  17. End Sub

After that, we have to adjust the table column according to the stored values in the array.

  1. Private Sub resizeTable(ByVal colSize() As Integer, ByVal table As TXTextControl.Table)
  2. Dim i As Integer
  3. Dim a As Integer
  4.  
  5. For a = 1 To table.Columns.Count
  6. If colSize.GetValue(i) = 0 Then
  7. Else
  8. table.Columns.GetItem(a).Width = colSize.GetValue(i) + 200
  9. End If
  10. i += 1
  11. Next
  12. End Sub

The minimum requirements for this sample application are TX Text Control .NET trial version and Visual Studio .NET 2003.

top

Top 10 Bestselling Product Award 2007Top 25 Publisher Product Award 2007Top 10 Bestselling Product Award 2007 in JapanTop 25 Bestselling Product Award 2006Top 25 Bestselling Publisher Award 2006Reader's Choice Award, dot.net magazin, 3rd place