Microsoft InfoPath 2010
The official blog of the Microsoft InfoPath team

Add items to a SharePoint list using managed code

Add items to a SharePoint list using managed code

Rate This
  • Comments 17

In this video demo, Phil Newman shows how you can write managed code in an InfoPath form to add items to a SharePoint list, and then publish this form as a sandboxed solution to SharePoint.

In InfoPath 2010, forms with code can now be published directly to SharePoint without requiring the farm administrator to approve and upload them! These forms run in a sandboxed environment which protects other resources on the SharePoint server from malicious code.

Get Microsoft Silverlight

For more details on publishing InfoPath forms with code as sandboxed solutions to SharePoint, see Phil’s earlier post Introduction to Sandboxed Solutions - Sort data in repeating tables using managed code.

Here’s the code that was used in this demo:

NOTE: To develop code using the SharePoint object model, you need to add a reference to Microsoft.SharePoint.dll to your VSTA project. This DLL is installed in %CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\ISAPI with your licensed copy of Microsoft SharePoint Server.

public void school_Changed(object sender, XmlEventArgs e)
  using (SPSite FormSite = new SPSite(ServerInfo.SharePointSiteUrl.ToString()))
    using (SPWeb FormWeb = FormSite.OpenWeb())
      //Get the list and query for the item - "Schools" is the name of the list I am retrieving
      SPList LookupList = FormWeb.Lists["Schools"];
      SPQuery MyQuery = new SPQuery();
      //"Title" is the field where I keep the school name
      ///my:myFields/my:school is the xpath to the school field
      MyQuery.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + GetDomValue("/my:myFields/my:school") + "</Value></Eq></Where>";
      SPListItemCollection ReturnedItems = LookupList.GetItems(MyQuery);
      //Add the item to the lookup list if no items were returned in the query
      if (ReturnedItems.Count == 0)
        SPListItem NewItem = LookupList.Items.Add();
        ///my:myFields/my:school is the xpath to the school field
        NewItem["Title"] = GetDomValue("/my:myFields/my:school");
        //Set AllowUnsafeUpdates = true to update the database
        FormWeb.AllowUnsafeUpdates = true;
        FormWeb.AllowUnsafeUpdates = false;
private string GetDomValue(string XpathToGet)
  return this.CreateNavigator().SelectSingleNode(XpathToGet, this.NamespaceManager).Value;
Leave a Comment
  • Please add 2 and 6 and type the answer here:
  • Post
  • Hi Santosh,

    You will need to convert this to VB.NET - I don't believe we have the same sample code in VB.NET - just C#.NET.


  • The video shows a black screen and nothing happens no activity, I have IE 11, tried with Chrome and Firefox, noway

Page 2 of 2 (17 items) 12