Tuesday 29 November 2011

Manipulate Infopath Dropdown List Through Managed Code

You cannot manipulate the form control directly, you can only manipulate the data source the control is bound. In the following example I have a data connection to get data from a SharePoint List, and the dropdown list has been configured to bind to the data connection. In the button click event I manually created a new item, append it to the list and then select that item.

public void CTRL6_5_Clicked(object sender, ClickedEventArgs e)
{
DataSource ds = this.DataSources["Customers"];
ds.QueryConnection.Execute();
XPathNodeIterator nodes = ds.CreateNavigator().Select("/dfs:myFields/dfs:dataFields/d:SharePointListItem_RW",this.NamespaceManager);
XPathNavigator lastNode = ds.CreateNavigator().SelectSingleNode("/dfs:myFields/dfs:dataFields/d:SharePointListItem_RW[" + nodes.Count.ToString() + "]", this.NamespaceManager);

XmlDocument doc = new XmlDocument();
XmlElement newNode = doc.CreateElement("d:SharePointListItem_RW", this.NamespaceManager.LookupNamespace("d"));
newNode.AppendChild(doc.CreateElement("d:Title", this.NamespaceManager.LookupNamespace("d"))).InnerText = "Jeff";
newNode.AppendChild(doc.CreateElement("d:ID", this.NamespaceManager.LookupNamespace("d"))).InnerText = "99";

lastNode.InsertAfter(newNode.OuterXml);

this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:field1", this.NamespaceManager).SetValue("Jeff");
}