DataTplAltFixDataMemberNotFound.vb
C# VB
'''' This code is part of Document Solutions for Word demos.'' Copyright (c) MESCIUS inc. All rights reserved.''Imports System.IOImports System.GlobalizationImports GrapeCity.Documents.Word
'' This example shows how to deal with the 'data source not found' error'' by ignoring non-existent data members.Public Class DataTplAltFixDataMemberNotFound '' Code demonstrating the problem: Private Function Problem() As GcWordDocument Using oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")) Dim doc = New GcWordDocument() doc.DataTemplate.DataSources.Add("ds", oceans) '' Incorrect: our data source does not have a member 'wrong_name': doc.Body.Paragraphs.Add("{{ds.wrong_name}}") doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US")) Return doc End Using End Function
'' Code demonstrating the fix: Private Function Fix() As GcWordDocument Using oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")) Dim doc = New GcWordDocument() doc.DataTemplate.DataSources.Add("ds", oceans) '' Still incorrect: our data source does not have a member 'wrong_name': doc.Body.Paragraphs.Add("{{ds.wrong_name}}") '' An alternative fix is to specify relaxed handling of missing fields, '' this will ignore such template tags bug will not throw exceptions: doc.DataTemplate.Options.MissingFieldsHandling = DataTemplateMissingFieldsHandling.Relaxed doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US")) Return doc End Using End Function
Function CreateDocx() As GcWordDocument Dim doc As GcWordDocument Try '' This fails: doc = Problem() Catch ex As Exception '' This works: doc = Fix() '' Insert a brief explanation of the problem and the fix into the generated document: doc.Body.Paragraphs.Insert( $"The error ""{ex.Message}"" occurred because in the template a non-existing path to a data member was used. " + $"To avoid exceptions in such cases, DataTemplate.Options.MissingFieldsHandling property can be set to " + $"DataTemplateMissingFieldsHandling.Relaxed. This will cause the template engine to ignore missing fields " + $"without throwing exceptions.", doc.Styles(BuiltInStyleId.BlockText), InsertLocation.Start) End Try Return doc End FunctionEnd Class