Wednesday, November 9, 2011

Inserting SharePoint List item using Silverlight Object Model

If you finally came over to the dark side and embraced Silverlight in SharePoint you should familarize yourself with the Client API for Silverlight, I have mentioned in a previous post how to reference these assemblies.

If you want to be more adventourous and insert list items using the Client API you can use the following code:
ClientContext context = ClientContext.Current;

List oList = context.Web.Lists.GetByTitle("HelloWorldList");

ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["Title"] = "Hello World";
oListItem.Update();

context.Load(oList, list => list.Title);
context.ExecuteQueryAsync(OnSuccess, OnFailed);
The above method is done assyncrously so you will have a call back which means if the insert is success code sample A if it is unsuccessful run code sample B, see below:
private void onSuccess(object sender, ClientRequestSucceededEventArgs args)
{
   Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
      MessageBox.Show("successfull");
   });
}
 private void onFailed(object sender, ClientRequestFailedEventArgsargs)
{
   Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
      MessageBox.Show("Failed");
   });
}
As you know these operations are done assyncronously so simply put we have to get the attention of the UI thread to perform our success or failure action.
Happy coding :-)