How to: Use Conditional Style

  • 3 minutes to read

The Rich Edit API allows you to set formatting rules to the specific table elements (first row, first cell, odd column, etc.). This feature is called conditional styles.

To create and apply a conditional style, perform the following steps.

  1. Create new table style using the TableStyleCollection.CreateNew method.
  2. Optionally, specify the newly created style's TableStyle.Parent property to derive it from an existing style.
  3. Create separate TableConditionalStyle objects for each desired table element type that needs to be formatted. To do so, call the TableConditionalStyleProperties.CreateConditionalStyle method repeatedly and pass different ConditionalTableStyleFormattingTypes enumeration values to this method as parameters.
  4. Specify additional settings for each TableConditionalStyle object you have:

  5. Add the style created in step 1 to the table styles collection by calling the TableCellStyleCollection.Add method. Note that styles not added to a corresponding collection cannot be applied to Rich Edit elements.
  6. To apply the style to a table, set this table's Table.Style property.
  7. Specify the table elements that should be formatted using the Table.TableLook property.

A complete sample project is available at

document.LoadDocument("Documents//TableStyles.docx", DocumentFormat.OpenXml);

// Create a new style that is based on the 'Grid Table 5 Dark Accent 1' style defined in the loaded document.
TableStyle myNewStyle = document.TableStyles.CreateNew();
myNewStyle.Parent = document.TableStyles["Grid Table 5 Dark Accent 1"];
// Create conditional styles (styles for table elements)
TableConditionalStyle myNewStyleForFirstRow = 
myNewStyleForFirstRow.CellBackgroundColor = Color.PaleVioletRed;
TableConditionalStyle myNewStyleForFirstColumn = 
myNewStyleForFirstColumn.CellBackgroundColor = Color.PaleVioletRed;
TableConditionalStyle myNewStyleForOddColumns = 
myNewStyleForOddColumns.CellBackgroundColor = System.Windows.Forms.ControlPaint.Light(Color.PaleVioletRed);
TableConditionalStyle myNewStyleForEvenColumns = 
myNewStyleForEvenColumns.CellBackgroundColor = System.Windows.Forms.ControlPaint.LightLight(Color.PaleVioletRed);
// Create a new table and apply a new style.
Table table = document.Tables.Create(document.Range.End, 4, 4, AutoFitBehaviorType.AutoFitToWindow);
table.Style = myNewStyle;
// Specify which conditonal styles are in effect.
table.TableLook = TableLookTypes.ApplyFirstRow | TableLookTypes.ApplyFirstColumn;


The image below illustrates the result of code execution.