Thursday, January 24, 2013

Silverlight Datagrid bind with list items

This will be helpful for the beginners to learn how to bind the silverlight datagrid control with SharePoint List Items in a list. Create the List name called "Friends" and create column FirstName,LastName,Email. Create the the class "MyFriends" and the data members using getter and setter to map with the sharepoint list columns. While retrieving the collection of items we will add the generic class of the "MyFriends" class and subsequently binding them to Silverlight datagrid.
  public class MyFriends
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string EmailID { get; set; }
            public int ItemID { get; set; }
        }

last member ItemID created for retrieving the item id for identify the each individual item from the collection of items for update and delete operation for further work.
        Web web;
        List list;
        ListItem item;
        ListItemCollection cols;
        private delegate void UpdateUI();


 public MainPage()
        {
            InitializeComponent();
            context = ClientContext.Current;
            web = context.Web;
            context.Load(web);
            list = web.Lists.GetByTitle("Friends");
            CamlQuery q = new CamlQuery();
            q.ViewXml = "";
            cols = list.GetItems(q);
            context.Load(cols);
            context.ExecuteQueryAsync(OnItemLoadSuccess, OnItemLoadFailed);
        }
        ClientContext context;
       
        private void OnItemLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUI _eventReg = BindItems;
            Dispatcher.BeginInvoke(_eventReg);
        }
        private void OnItemLoadFailed(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Error" + e.StackTrace.ToString());
        }
        public void BindItems()
        {
            List obj = new List();
            foreach (ListItem item in cols)
            {
                obj.Add(new MyFriends
                {
                    FirstName = item["First_x0020_Name"].ToString(),
                    LastName = item["First_x0020_Name"].ToString(),
                    EmailID = item["EmailID"].ToString(),
                    ItemID = Convert.ToInt32(item["ID"])
                });
                dataGrid1.ItemsSource = obj;
            }
        }