TX Text Control Source Code Library

TX Text Control Table Indent Alignment

If a table is inserted in existing text, it is often a requirement to align the table to the text.

To accomplish that, both the width and the starting point of a table have to be set programmatically.

This sample project uses TX Text Control to provide a similar feature as seen in Microsoft Word, where tables are automatically aligned to the paragraph indent.

To get the actual available space for the table width, availableWidth, the current page and paragraph settings are taken into account:

double availableWidth = textControl1.Sections.GetItem().Format.PageSize.Width * 14.4 - textControl1.Sections.GetItem().Format.PageMargins.Left * 14.4 - textControl1.Sections.GetItem().Format.PageMargins.Right * 14.4 - textControl1.Selection.ParagraphFormat.LeftIndent - textControl1.Selection.ParagraphFormat.HangingIndent - textControl1.Selection.ParagraphFormat.RightIndent;

To calculate the new width for all table cells, the current table width and delta to the available space are calculated:

for (int i = rows; i >= 1; i--) { double curWidth = 0; // iterate all table columns and calculate the current width of the table for (int e = columns; e >= 1; e--) { curWidth += textControl1.Tables.GetItem(tableID).Cells.GetItem(i, e).Width; } // calculate delta for changing the table width double percentageDelta = availableWidth / curWidth; [...]

After that, the starting position for the table based on the alignment is set:

int tableStart = textControl1.Selection.ParagraphFormat.LeftIndent; [...] textControl1.Tables.GetItem(tableID).Columns.GetItem(1).Position = tableStart;

When actually resizing the table, each cell's width is set. Additionally, I implemented keepIndentInCells to keep or remove the paragraph alignment for the table cells.

for (int e = columns; e >= 1; e--) { double newWidth = textControl1.Tables.GetItem(tableID).Cells.GetItem(i, e).Width * percentageDelta; textControl1.Tables.GetItem(tableID).Cells.GetItem(i, e).Width = (int)newWidth; if (!keepIndentInCells) { textControl1.Selection.Start = textControl1.Tables.GetItem(tableID).Cells.GetItem(i, e).Start - 1; textControl1.Selection.ParagraphFormat.LeftIndent = 0; textControl1.Selection.ParagraphFormat.RightIndent = 0; textControl1.Selection.ParagraphFormat.HangingIndent = 0; } }

The minimum requirements for this sample application are TX Text Control .NET for Windows Forms trial version 14 and Visual Studio 2005.

 
 

Products

Support

Downloads

Corporate

Buy Now