Friday, 6 April 2012

Add Person/Group field to a SharePoint list from Webpart

I created a new list with person/group field as follows
Then create a WebPart with checkbox list which displays the users and button to add user to the list.
The following code explains how to do this.....

formula to add a user
<UserID>;#<UserLoginName>


using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace userselect
{
    [Guid("cdcee41f-cb36-42eb-b2d8-36af57fbcbd8")]
    public class userselect : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;
        private string _myProperty = null;
        Dictionary<int,string> UserInfo= new Dictionary<int,string>();
        Button AddUser;
        TextBox txtInfo;
        CheckBoxList UserList;
        public userselect()
        {
            this.ExportMode = WebPartExportMode.All;
        }
   protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {

                    base.CreateChildControls();
                    UserList = new CheckBoxList();
                    Get_UserList();
                    UserList.ID = "UserList";
                    UserList.DataSource =UserInfo;
                    UserList.DataValueField = "Key";
                    UserList.DataTextField = "Value";
                    UserList.DataBind();
                    Controls.Add(UserList);

                    AddUser = new Button();
                    AddUser.ID = "AddUser";
                    AddUser.Text = "Add User";
                    AddUser.Click += new EventHandler(AddUser_Click);
                    this.Controls.Add(AddUser);

                 }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        void AddUser_Click(object sender, EventArgs e)
        {
        string temp=string.Empty;
        SPSite site = new SPSite("http://url");
        SPWeb web = site.OpenWeb();

            for (int index = 0; index < UserList.Items.Count; index++)
            {
                if (UserList.Items[index].Selected)
                {
                int id=int.Parse(UserList.Items[index].Value);
                temp = id.ToString()+";#"+web.Users.GetByID(id).LoginName+";#";
               }
            }
            txtInfo.Text = temp;
//remove the extra symbol
            if (temp.EndsWith(";#"))
            {
                temp = temp.Substring(0, temp.Length - 2);
            }

            SPList list = web.Lists["newlist"];
            SPListItem item = list.Items.Add();

            item["Title"] = "from sugu";
            item["user"] = temp;
            item.Update();


        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    // Your code here...
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }


        private void Get_UserList()
        {
            UserInfo.Clear();
           
            SPSite site = new SPSite("http://url");
            SPWeb web = site.OpenWeb();
           // I need the users only from the viewers group
            SPGroup group = web.Groups["Viewers"];
           
            foreach (SPUser user in group.Users)
            {
                UserInfo.Add(user.ID, user.Name);
               
            }
          
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }
    }
}


Happy coding :)