Update field switches of mail merge field using C#

Hi,

I’m trying to update a mergefield with a Date picturecode in a template file.

There are 2 are alsmost identical template files. The first has an English content and the second has some Dutch content. But all the mergefields are identical.

For some reason I’m getting an incomplete fieldcode for tne dutch version of the document.

Sample code:

doc = new Document(fileName);
foreach (FieldStart start in starts)
{
if (start.FieldType == FieldType.FieldMergeField)
{

// get the fieldcode
Run fieldCode = start.NextSibling as Run;
Console.WriteLine("fieldCode.Text);
// get the fieldcode with another function
Console.WriteLine(GetFieldCode(start.NextSibling));

// Update FieldCode
if (fieldCode.Text.IndexOf(@"@") > 0)
{
fieldCode.Text = fieldData.Replace(".", “-”);
}
}
}

///

/// Retrieves the field code from a field.
///

/// The field start of the field which to gather the field code from
///
private static string GetFieldCode(FieldStart fieldStart)
{
StringBuilder builder = new StringBuilder();
for (Node node = fieldStart; node != null && node.NodeType != NodeType.FieldSeparator && node.NodeType != NodeType.FieldEnd; node = node.NextPreOrder(node.Document))
{
// Use text only of Run nodes to avoid duplication.
if (node.NodeType == NodeType.Run)
builder.Append(node.GetText());
}
return builder.ToString();
}

Result for the English version:
MERGEFIELD DateStart @ “dd.MM.yy”
MERGEFIELD DateStart @ “dd.MM.yy”

Result for the dutch version:
MERGEFIELD DateStart @ "dd
MERGEFIELD DateStart @ “dd.MM.yy”

When I debug the GetFieldCode function I see that for the Dutch version the DateField exist from 6 different Run components.

Can you help me overcome this problem? Because the info from the dutchversion is incomplete the replace of the “.” won’t work
I have attached the 2 templatefiles

Dirk Molman

Hi Dirk,

Thanks for your query. You can overcome your problem by using following code snippet.

Document doc = new Document(DirDoc + "2.01_NL_Reservation.doc");

NodeCollection starts = doc.GetChildNodes(NodeType.FieldStart, true);

foreach (FieldStart start in starts){

if (start.FieldType == FieldType.FieldMergeField){

String fieldcode = GetFieldCode(start);

if (fieldcode.IndexOf(@"\@") > 0){

Node current = start;

while (current.NodeType != NodeType.FieldEnd){

if (current.NodeType == NodeType.Run){

(current as Run).Text = (current as Run).Text.Replace(".", "-");

}
current = current.NextSibling;

}

}

}

}