Tuesday, January 15, 2013

Adding new item silverlight with sharepoint

This code will help you to start the journey on How to develop SilverLight WebPart using SharePoint Client Side Object Model to add new item in SharePoint List.

Add the following sharepoint related assemblies which specifically tailored for the SilverLight and its Client side object model.

Microsoft.SharePoint.Client.SilverLight; Microsoft.SharePoint.Client.SilverLight.Runtime; These assemblies located at

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin
namespace SilverlightApplication7
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private delegate void UpdateUI();
        private ClientContext ctx;
        private Web web;
       
        List list;
     
        ListItem item;

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ctx = ClientContext.Current;
            web = ctx.Web;
            ctx.Load(web);
            list = web.Lists.GetByTitle("Friends");
            ctx.Load(list);
            ListItemCreationInformation info = new ListItemCreationInformation();
            item = list.AddItem(info);
            item["Title"] = textBox1.Text;
            item["Name"] = textBox2.Text;
          
            item.Update();
            ctx.Load(item);
            ctx.ExecuteQueryAsync(OnOperationSuccess, OnOperationFailure);
           
        }
        public void ShowSuccessMessage()
        {
          
            MessageBox.Show("Added","Silverlight with SharePoint",MessageBoxButton.OK);
            textBox1.Text = "";
            textBox2.Text = "";
        }
        public void OnOperationSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUI obj = ShowSuccessMessage;
            this.Dispatcher.BeginInvoke(obj);
        }
        public void OnOperationFailure(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show(e.Message.ToString());
        }
    }
}