Friday, September 16, 2011

How to Get SPUser Collections from SPListItem

In my previous post I have shown the code snippet to fetch SPUser from ListItem, now at times the user field may contain more than one user. It all depends on how you configure the list column. If you check the box for multiple user then the field will allow to add multiple users. In such a scenarios you need to use the below code stub.  

# #region Get SP User(s)

        private List<SPUser> GetSPUser1(SPListItem item, string ColumnName)

        {

            ////Get field/column from List Item

            SPFieldUser field = item.Fields[ColumnName] as SPFieldUser;

            List<SPUser> MySPUserCollection = new List<SPUser>();

            if (field != null && item[ColumnName] != null)

            {

                ////If the Field/Column allows multiple users, then the field will have a collection of User values

                SPFieldUserValueCollection oFieldColl = field.GetFieldValue(item[ColumnName].ToString()) as SPFieldUserValueCollection;

                ////See if the collection has got users

                if (oFieldColl.Count > 0)

                {

                    for (int i = 0; i <= oFieldColl.Count; i++)

                    {

                        MySPUserCollection.Add(oFieldColl[0].User);

                    }

                }

            }

            return MySPUserCollection;

        }

        #endregion

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

 

No comments:

Post a Comment