Problem: You have a text box control on an InfoPath form and want to display a list of errors that have been raised for the data entered into the text box.
You can use the Errors property of a form to retrieve error messages for a field.
1 - Create a new form template and add two Text Boxes control to the page and name it "field2" and "Errors".
2 - Select the Text Box and select its Cannot Be Blank property.
3 - Add two Button control to the form and label them "Set User-Defined Errors" and "Get All Errors".
4 - For the Clicked() event handler of the "Set User-Defined Errors" button add:
Dim field2 As XPathNavigator = MainDataSource.CreateNavigator.SelectSingleNode("/my:myFields/my:field2", NamespaceManager)
Errors.Add(field2, "Error1", "This is error 1.")
Errors.Add(field2, "Error2", "This is error 2.")
Errors.Add(field2, "Error3", "This is error 3.")
This code should raise three user-defined errors on the text box.
5 - For the Clicked() event handler of the "Get All Errors" button add:
Dim sb As New System.Text.StringBuilder
For Each err As FormError In Errors
sb.AppendFormat("Form Error Type: {0} - ", err.FormErrorType)
sb.AppendFormat("Message: {0}", err.Message)
sb.AppendLine()
Next
MainDataSource.CreateNavigator.SelectSingleNode("/my:myFields/my:Errors", NamespaceManager).SetValue(sb.ToString)
6 - Save and preview the form
When the form opens click the "Get All Errors" button and you should see error messages appear in the errors text box. After that click on the "Set User-Defined Errors" button and then click on the "Get All Errors" button again. You will that the three user-defined errors should appear in the errors text box.
ps. Use "err.Site.LocalName" if you would like to retrieve the name of field on which the error occurred.
The following code:
sb.AppendFormat("The field " & err.Site.LocalName & " has the following error: " & err.Message)
Renders:
The field salary has the following error: Cannot be blank
No comments:
Post a Comment