How to: Insert a Table

  • 2 min to read

The following example illustrates how to insert a table to the document.

To create a new table, use the TableCollection.Create method. This method creates a table and adds it to the TableCollection, accessible through the SubDocument.Tables property.

To insert data to the table, use the SubDocument.InsertText or SubDocument.InsertSingleLineText method. Use the table cell starting position as the method's argument.

NOTE

A complete sample project is available at https://github.com/DevExpress-Examples/wpf-richedit-document-api-t213968.

// Insert new table.
Table tbl = document.Tables.Create(document.Range.Start, 1, 3, AutoFitBehaviorType.AutoFitToWindow);
// Create a table header.
document.InsertText(tbl[0, 0].Range.Start, "Name");
document.InsertText(tbl[0, 1].Range.Start, "Size");
document.InsertText(tbl[0, 2].Range.Start, "DateTime");
// Insert table data.
DirectoryInfo dirinfo = new DirectoryInfo("C:\\");
try
{
    tbl.BeginUpdate();
    foreach (FileInfo fi in dirinfo.GetFiles())
    {
        TableRow row = tbl.Rows.Append();
        TableCell cell = row.FirstCell;
        string fileName = fi.Name;
        string fileLength = String.Format("{0:N0}", fi.Length);
        string fileLastTime = String.Format("{0:g}", fi.LastWriteTime);
        document.InsertSingleLineText(cell.Range.Start, fileName);
        document.InsertSingleLineText(cell.Next.Range.Start, fileLength);
        document.InsertSingleLineText(cell.Next.Next.Range.Start, fileLastTime);
    }
    // Center the table header.
    foreach (Paragraph p in document.Paragraphs.Get(tbl.FirstRow.Range))
    {
        p.Alignment = ParagraphAlignment.Center;
    }
}
finally
{
    tbl.EndUpdate();
}