InfoPath Dynamic Hyperlink Field C# and Code Behind

In InfoPath, dynamically update a hyperlink field using code.
Sounded simple, but it took me a few minutes to get it straightened out.

I’ve attached the InfoPath form and the code behind files here:

Create a new Blank InfoPath form.

Add a Hyperlink control to the form.

In this step, I’ve set the field to Read-Only. Why? I didn’t want the user to be able to modify the field.

Change the field names. The first field (field1) is the field that will hold the URL path. The second field (field2) will hold the text that you want to display in place of the URL.

I’ve updated my fields as follows:
field1 changed to URLpath
field2 changed to URLdisplay

To quickly test this post, click on the Developer tab, then click Loading Event.

        public void FormEvents_Loading(object sender, LoadingEventArgs e)
            XPathNavigator ipFormNav = MainDataSource.CreateNavigator();
            XPathNavigator assnAttachURL = ipFormNav.SelectSingleNode("/my:myFields/my:URLpath", NamespaceManager);
            XPathNavigator assnAttachDisplay = ipFormNav.SelectSingleNode("/my:myFields/my:URLpath/@my:URLdisplay", NamespaceManager);

            //Update the URL path to a document on your site.

To get the correct XPath values, see the screenshot below.

To see this work, in the code editor, click on Build, then Start Debugging.