Thursday, August 21, 2008

Reset functionality for InfoPath

Something I really miss in InfoPath 2007 is the possibility to have a simple "reset" button, one that clears all your fields and lets you start all over. I didn't find any out-of-the-box functionality for this, so I wrote some code to make this work. So if you're looking for something that clears all your datasource's fields, try this piece of code:

private void ClearAllFields()
{
   //Create a navigator and select the first group in your datasource
   XPathNavigator nav = this.MainDataSource.CreateNavigator();
   XPathNodeIterator nodes = nav.SelectSingleNode("/my:myFields/my:group1", NamespaceManager).SelectChildren(XPathNodeType.Element);

   ClearLevel(nodes);
}

private void ClearLevel(XPathNodeIterator nodes)
{
   while (nodes.MoveNext())
   {
      if (nodes.Current.HasChildren)
      {
         ClearLevel(nodes.Current.SelectChildren(XPathNodeType.All));
      }

      if (nodes.Current.NodeType == XPathNodeType.Text)
      {
         //Reset the value to an empty string
         nodes.Current.SetValue("");
      }
   }
}

Just put the ClearAllFields() method in your button.clicked event handler and it should all work just fine! Make sure you select the right node to start with. Replace the "/my:myFields/my:group1" with the path to your top level group.

1 comment:

Anonymous said...

Thanks a zillion for this Tom.

IJ