Add items to a SharePoint list using managed code

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;
        NewItem.Update();
        FormWeb.AllowUnsafeUpdates = false;
      }
    }
  }
}
private string GetDomValue(string XpathToGet)
{
  return this.CreateNavigator().SelectSingleNode(XpathToGet, this.NamespaceManager).Value;
}