Set date picker value in InfoPath programmatically

04/06/2014 11:31

Only date format "yyyy-MM-dd" or datime "yyyy-MM-ddTHH:mm:ss" is accepted by Infopath

you have to remove nil value if there


DateTime date = DateTime.Today;
DateTime nextDayDate = (DateTime)date.Value.AddDays(1);


string nextDateString = nextDayDate.ToString("yyyy-MM-dd");
              
XPathNavigator endDateNode = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:yourTargetDatePickerField", NamespaceManager);
              
                if (endDateNode.MoveToAttribute("nil", "https://www.w3.org/2001/XMLSchema-instance"))
                    endDateNode.DeleteSelf();

                endDateNode.SetValue(nextDateString );


so, generally


 DateTime dateTime = DateTime.Now;
            string dateString = dateTime.ToString("yyyy-MM-dd");
            string dateTimeStrng = dateTime.ToString("yyyy-MM-ddTHH:mm:ss");


            //this node is Date type
            XPathNavigator endDateNode = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:DatumNastupu", NamespaceManager);
            //XPathNavigator endDateNode = XNode("/my:myFields/my:DatumNastupu");

            if (endDateNode.MoveToAttribute("nil", "https://www.w3.org/2001/XMLSchema-instance"))
                endDateNode.DeleteSelf();
            endDateNode.SetValue(dateString);

            //this node is DateTime type
            XPathNavigator dateTimeNode = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:DateTimeField", NamespaceManager);
            if (dateTimeNode.MoveToAttribute("nil", "https://www.w3.org/2001/XMLSchema-instance"))
                dateTimeNode.DeleteSelf();
            dateTimeNode.SetValue(dateTimeStrng);


or functions for use for Date field type or DateTime field type

public void SetDateToXNode(string xpath, DateTime date)
        {
            XPathNavigator dateNode = MainDataSource.CreateNavigator().SelectSingleNode(xpath, NamespaceManager);

            if (dateNode.MoveToAttribute("nil", "https://www.w3.org/2001/XMLSchema-instance"))
                dateNode.DeleteSelf();
            dateNode.SetValue(date.ToString("yyyy-MM-dd"));
        }

        public void SetDateTimeToXNode(string xpath, DateTime dateTime)
        {
            XPathNavigator dateNode = MainDataSource.CreateNavigator().SelectSingleNode(xpath, NamespaceManager);

            if (dateNode.MoveToAttribute("nil", "https://www.w3.org/2001/XMLSchema-instance"))
                dateNode.DeleteSelf();
            dateNode.SetValue(dateTime.ToString("yyyy-MM-ddTHH:mm:ss"));
        }



SetValue(dateTimeStrng);