officefileapi-devexpress-dot-xtrarichedit-dot-richeditdocumentserver-28deb756.md
Fires when the DOCVARIABLE field is updated.
Namespace : DevExpress.XtraRichEdit
Assembly : DevExpress.RichEdit.v25.2.Core.dll
NuGet Package : DevExpress.RichEdit.Core
public event CalculateDocumentVariableEventHandler CalculateDocumentVariable
Public Event CalculateDocumentVariable As CalculateDocumentVariableEventHandler
The CalculateDocumentVariable event's data class is CalculateDocumentVariableEventArgs. The following properties provide information specific to this event:
| Property | Description |
|---|---|
| Arguments | Provides access to a collection of arguments within the DOCVARIABLE field. |
| FieldLocked | Gets or sets a locked attribute to the field for which the event occurs. |
| Handled | Gets or sets whether the default action is required. |
| KeepLastParagraph | Gets or sets whether the last paragraph of the inserted document is kept in the resulting document. |
| PreserveInsertedContentFormatting | Gets or sets whether to insert an additional hidden paragraph so that the inserted content is not formatted with the DOCVARIABLE field’s paragraph formatting. |
| Value | Gets or sets the value of the DOCVARIABLE field that fired the event. |
| VariableName | Gets the name of the document variable to which the DOCVARIABLE field refers. |
The CalculateDocumentVariable event fires when one of the following operations with a DOCVARIABLE field occurs:
Handle this event to analyze DOCVARIABLE field switches and arguments, and specify custom content to insert into this field.
Assign a DocVariableValue.Current value to the CalculateDocumentVariableEventArgs.Value property and set e.Handled to true to retain the existing DOCVARIABLE value.
You can specify the FieldOptions.UpdateLockedFields property to raise the event for locked DOCVARIABLE fields.
Use the CalculateDocumentVariableEventArgs.FieldLocked property to lock/unlock the field in the CalculateDocumentVariable handler. Set e.Handled to true to apply changes.
If you use the RichEditDocumentServer.MailMerge method to evaluate nested DOCVARIABLE fields, set the RichEditMailMergeOptions.ViewMergedData option to true. Otherwise, you get field placeholders instead of values in the CalculateDocumentVariable handler.
Check the field’s CalculateDocumentVariableEventArgs.Arguments value to retrieve a nested field value. When the CalculateDocumentVariable event is fired for the first time, e.Arguments contains the <<FieldName_1>> (the placeholder for the field), because the merge field has not yet been calculated. In this case, do nothing in the event handler (use comparison and return statements if required).
Note
If you use the MailMerge method overload with a document parameter, handle the CalculateDocumentVariable event of a SubDocument passed as a parameter instead of the RichEditDocumentServer.CalculateDocumentVariable event.
The following code snippet handles the event to calculate the DOCVARIABLE field value. In this example, this field should insert the number of years the employee worked at a company. The nested MERGEFIELD refers to the HireDate entry in the database.
private static void WordProcessor_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e)
{
if (e.Arguments.Count > 0)
{
// Retrieve the MERGEFIELD field value
DateTimeOffset hireDate = Convert.ToDateTime(e.Arguments[0].Value);
DateTimeOffset currentDate = DateTime.Now;
// Calculate the difference between the current date
// and the hire date
var dif = currentDate.Subtract(hireDate);
// Calculate the number of years
int years = dif.Days / 365;
// Specify the DOCVARIABLE field value
e.Value = years.ToString();
e.Handled = true;
}
e.Handled = true;
}
Private Shared Sub WordProcessor_CalculateDocumentVariable(ByVal sender As Object, ByVal e As CalculateDocumentVariableEventArgs)
If e.Arguments.Count > 0 Then
' Retrieve the MERGEFIELD field value
Dim hireDate As DateTimeOffset = Convert.ToDateTime(e.Arguments(0).Value)
Dim currentDate As DateTimeOffset = DateTime.Now
' Calculate the difference between the current date
' and the hire date
Dim dif = currentDate.Subtract(hireDate)
' Calculate the number of years
Dim years As Integer = dif.Days \ 365
' Specify the DOCVARIABLE field value
e.Value = years.ToString()
e.Handled = True
End If
e.Handled = True
End Sub
View Example: Use DOCVARIABLE Fields
This code snippet demonstrates how to handle the Document.CalculateDocumentVariable event to insert dynamic content into the document. In this example, it is used to get weather conditions. A variable name specified in the DOCVARIABLE indicates a choice between location and weather, while the location itself is specified by the field argument.
private static void Document_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e) {
if (e.Arguments.Count > 0) {
string location = e.Arguments[0].Value.ToString();
if ((location.Trim() == String.Empty) || (location.Contains("<"))) {
e.Value = " ";
e.Handled = true;
return;
}
switch (e.VariableName) {
case "Weather":
Conditions conditions = new Conditions();
conditions = Weather.GetCurrentConditions(location);
e.Value = String.Format("Weather for {0}: \nConditions: {1}\nTemperature (C) :{2}\nHumidity: {3}\nWind: {4}\n",
location, conditions.Condition, conditions.TempC, conditions.Humidity, conditions.Wind);
break;
case "LOCATION":
if (location == "DO NOT CHANGE!") e.Value = DocVariableValue.Current;
break;
default:
e.Value = "LOCKED FIELD UPDATED";
break;
}
}
else {
e.Value = "LOCKED FIELD UPDATED";
}
e.Handled = true;
}
Private Shared Sub Document_CalculateDocumentVariable(ByVal sender As Object, ByVal e As CalculateDocumentVariableEventArgs)
If e.Arguments.Count > 0 Then
Dim location As String = e.Arguments(0).Value.ToString()
If (location.Trim() = String.Empty) OrElse (location.Contains("<")) Then
e.Value = " "
e.Handled = True
Return
End If
Select Case e.VariableName
Case "Weather"
Dim conditions As Conditions = New Conditions()
conditions = Weather.GetCurrentConditions(location)
e.Value = String.Format("Weather for {0}: " & vbLf & "Conditions: {1}" & vbLf & "Temperature (C) :{2}" & vbLf & "Humidity: {3}" & vbLf & "Wind: {4}" & vbLf, location, conditions.Condition, conditions.TempC, conditions.Humidity, conditions.Wind)
Case "LOCATION"
If location = "DO NOT CHANGE!" Then e.Value = DocVariableValue.Current
Case Else
e.Value = "LOCKED FIELD UPDATED"
End Select
Else
e.Value = "LOCKED FIELD UPDATED"
End If
e.Handled = True
End Sub
The code sample below shows how to handle the RichEditDocumentServer.CalculateDocumentVariable event to insert a barcode and a table:
using (var wordProcessor = new RichEditDocumentServer()) {
wordProcessor.CreateNewDocument();
Document document = wordProcessor.Document;
// Create fields for a barcode and a table:
document.Fields.Create(document.Range.End, "DOCVARIABLE QRCODE");
document.Paragraphs.Append();
document.Fields.Create(document.Range.End, "DOCVARIABLE TABLE");
wordProcessor.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable;
// Update all document fields:
document.UpdateAllFields();
// Save the result:
wordProcessor.SaveDocument("result.docx", DocumentFormat.Docx);
}
void WordProcessor_CalculateDocumentVariable(object sender, CalculateDocumentVariableEventArgs e) {
switch (e.VariableName) {
case "QRCODE":
// Create new RichEditDocumentServer instance:
var doc = new RichEditDocumentServer();
// Insert a barcode as a shape
Shape picture = doc.Document.Shapes.InsertPicture(doc.Document.Range.End, GenerateQrCode());
picture.TextWrapping = TextWrappingType.InLineWithText;
// Set the field value to the RichEditDocumentServer instance:
e.Value = doc;
e.Handled = true;
break;
case "TABLE":
// Create new RichEditDocumentServer instance:
var doc1 = new RichEditDocumentServer();
// Insert a table:
GenerateTable(doc1.Document);
// Set the field value to the RichEditDocumentServer instance:
e.Value = doc1;
e.Handled = true;
break;
}
}
// This method generates a barcode:
static Bitmap GenerateQrCode() {
BarCode barCode = new BarCode();
barCode.Symbology = Symbology.QRCode;
barCode.CodeText = "https://www.devexpress.com/";
barCode.BackColor = Color.White;
barCode.ForeColor = Color.Black;
barCode.RotationAngle = 0;
barCode.CodeBinaryData = Encoding.Default.GetBytes(barCode.CodeText);
barCode.Options.QRCode.CompactionMode = QRCodeCompactionMode.Byte;
barCode.Options.QRCode.ErrorLevel = QRCodeErrorLevel.Q;
barCode.Options.QRCode.ShowCodeText = false;
barCode.DpiX = 72;
barCode.DpiY = 72;
barCode.Module = 2f;
return barCode.BarCodeImage;
}
// This method generates a table:
static Table GenerateTable(Document document) {
Table table = document.Tables.Create(document.Range.Start, 3,3);
document.InsertSingleLineText(table.Rows[0].Cells[1].Range.Start, "Active Customers");
document.InsertSingleLineText(table[1, 0].Range.Start, "Photo");
document.InsertSingleLineText(table[1, 1].Range.Start, "Customer Info");
document.InsertSingleLineText(table[1, 2].Range.Start, "Rentals");
return table;
}
Using wordProcessor = New RichEditDocumentServer()
wordProcessor.CreateNewDocument()
Dim document As Document = wordProcessor.Document
document.Fields.Create(document.Range.End, "DOCVARIABLE QRCODE")
document.Paragraphs.Append()
document.Fields.Create(document.Range.End, "DOCVARIABLE TABLE")
wordProcessor.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable
document.UpdateAllFields()
wordProcessor.SaveDocument("result.docx", DocumentFormat.Docx)
End Using
Private Sub WordProcessor_CalculateDocumentVariable(ByVal sender As Object, ByVal e As CalculateDocumentVariableEventArgs)
Select Case e.VariableName
Case "QRCODE"
Dim doc = New RichEditDocumentServer()
Dim picture As Shape = doc.Document.Shapes.InsertPicture(doc.Document.Range.End, GenerateQrCode())
picture.TextWrapping = TextWrappingType.InLineWithText
e.Value = doc
e.Handled = True
Case "TABLE"
Dim doc1 = New RichEditDocumentServer()
GenerateTable(doc1.Document)
e.Value = doc1
e.Handled = True
End Select
End Sub
Shared Function GenerateQrCode() As Bitmap
Dim barCode As New BarCode()
barCode.Symbology = Symbology.QRCode
barCode.CodeText = "https://www.devexpress.com/"
barCode.BackColor = Color.White
barCode.ForeColor = Color.Black
barCode.RotationAngle = 0
barCode.CodeBinaryData = Encoding.Default.GetBytes(barCode.CodeText)
barCode.Options.QRCode.CompactionMode = QRCodeCompactionMode.Byte
barCode.Options.QRCode.ErrorLevel = QRCodeErrorLevel.Q
barCode.Options.QRCode.ShowCodeText = False
barCode.DpiX = 72
barCode.DpiY = 72
barCode.Module = 2F
Return barCode.BarCodeImage
End Function
Shared Function GenerateTable(ByVal document As Document) As Table
Dim table As Table = document.Tables.Create(document.Range.Start, 3,3)
document.InsertSingleLineText(table.Rows(0).Cells(1).Range.Start, "Active Customers")
document.InsertSingleLineText(table(1, 0).Range.Start, "Photo")
document.InsertSingleLineText(table(1, 1).Range.Start, "Customer Info")
document.InsertSingleLineText(table(1, 2).Range.Start, "Rentals")
Return table
End Function
The following code snippets (auto-collected from DevExpress Examples) contain references to the CalculateDocumentVariable event.
Note
The algorithm used to collect these code examples remains a work in progress. Accordingly, the links and snippets below may produce inaccurate results. If you encounter an issue with code examples below, please use the feedback form on this page to report the issue.
word-document-api-create-master-detail-report/CS/Program.cs#L52
myMergeOptions.MergeMode = MergeMode.NewSection;
wordProcessor.CalculateDocumentVariable += WordProcessor_OnCalculateDocumentVariable;
winforms-richedit-use-calculatedocumentvariable-event-to-insert-formatted-content/CS/Form1.cs#L37
server.CalculateDocumentVariable += new CalculateDocumentVariableEventHandler(Document_CalculateDocumentVariable);
richEditControl1.Document.MailMerge(myMergeOptions, server.Document);
word-document-api-insert-dynamic-content/CS/Program.cs#L21
InsertDocVariableField(wordProcessor.Document);
wordProcessor.CalculateDocumentVariable += WordProcessor_CalculateDocumentVariable;
wordProcessor.Document.Fields.Update();
word-document-api-examples/CS/CodeExamples/DocumentPropertiesActions.cs#L67
wordProcessor.CalculateDocumentVariable += (s, e) =>
{
winforms-richedit-use-calculatedocumentvariable-event-to-insert-formatted-content/VB/Form1.vb#L29
Dim server As RichEditDocumentServer = New RichEditDocumentServer()
AddHandler server.CalculateDocumentVariable, New CalculateDocumentVariableEventHandler(AddressOf Document_CalculateDocumentVariable)
richEditControl1.Document.MailMerge(myMergeOptions, server.Document)
word-document-api-insert-dynamic-content/VB/Module1.vb#L16
InsertDocVariableField(wordProcessor.Document)
AddHandler wordProcessor.CalculateDocumentVariable, AddressOf WordProcessor_CalculateDocumentVariable
wordProcessor.Document.Fields.Update()
word-document-api-examples/VB/CodeExamples/DocumentPropertiesActions.vb#L56
document.CustomProperties("MyBooleanProperty") = True
AddHandler wordProcessor.CalculateDocumentVariable,
Sub(s, e)
See Also
How to: Insert Dynamic Content