InfoPath setting date value with code behind

Format matters! So if you ever tried to set a date value to an infopath form by using code behind, you might got this really nice displaying with a beautiful red dotted border:

Why? It’s easy – cause you have to format the date in the right way InfoPath expects it! InfoPath expects it this way: yyyy-mm-dd.

Well that’s easy. But in order to overwrite the value of a datefield, you have to insert these lines of code in order to overwrite a date field with string values! So i didn’t test it without this function:

[sourcecode language=”csharp”]

public void DeleteNil(XPathNavigator node)
{
if (node.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance“))
node.DeleteSelf();
}

[/sourcecode]

After that you can use this function in order to set attribute and overwrite the field by setting the value as you desire.

[sourcecode language=”csharp”]

//In order to overwrite the field with datetime

//Opening the access to the field of the form
XPathNavigator navForm = this.CreateNavigator();
XmlNamespaceManager NS = this.NamespaceManager;

DeleteNil(navForm.SelectSingleNode(“/my:meineFelder/my:CreationDay”, NS));

DateTime getDate = Convert.ToDateTime(dr[“CreateDate”]);

string convDate = getDate.ToString(“yyyy-MM-dd”);

navForm.SelectSingleNode(“/my:meineFelder/my:CreationDay”, NS).SetValue(convDate);

[/sourcecode]

And it looks like a normal date field:

As you can see the red dotted validation does not show up.

..:: I like SharePoint ::..

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

About Karsten Schneider 312 Articles
Consultant for Microsoft 365 Applications with a strong focus in Teams, SharePoint Online, OneDrive for Business as well as PowerPlatform with PowerApps, Flow and PowerBI. I provide Workshops for Governance & Security in Office 365 and Development of Solutions in the area of Collaboration and Teamwork based on Microsoft 365 and Azure Cloud Solutions. In his free time he tries to collect tipps and worthy experience in this blog.