Sunday 9 March 2014

SharePoint get Person or Group Column data using C#

SharePoint get Person or Group Column data using C#
using (SPSite oSite = new SPSite(“http://SP”))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPList oList = oWeb.Lists["My List Name"];
SPListItem oItem = oList.GetItemById(1);
SPFieldUserValue userValue = new SPFieldUserValue(oWeb, oItem["Person or Group Column Name"].ToString());
SPUser userVal = userValue.User;
}
}
Read SharePoint List Items using C#
using (SPSite siteCol = new SPSite("http://server/sites/Contoso"))
{
using (SPWeb web = siteCol.RootWeb)
{
SPList list = web.GetList("/sites/Contoso/Lists/Books");
SPListItem item = list.GetItemByIdSelectedFields(3, "Title", "ISBN", "Retail_x0020_Price");
String bookISBN = (String)item["ISBN"];
}
}
I have provided 2 examples to read list columns.
You will get doubt which one i have to use...

SPWeb.Lists Vs SPWeb.GetList

SPWeb.GetList (string strUrl)
----------------------------
using (SPSite siteCol = new SPSite("http://server/sites/Contoso"))
{
using (SPWeb web = siteCol.RootWeb)
{
SPList list = web.GetList("/sites/Contoso/Lists/Books");
SPListItem item = list.GetItemByIdSelectedFields(3, "Title", "ISBN", "Retail_x0020_Price");
String bookISBN = (String)item["ISBN"];
}
}
ABove code first retrieves the list GUID from the url, from sharepoint database, then it loads the metadata for that specific list. Performace of this code is good and high...
SPWeb.Lists (“ListName”)
--------------------------
using (SPSite oSite = new SPSite(“http://SP”))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPList oList = oWeb.Lists["My List Name"];
SPListItem oItem = oList.GetItemById(1);
SPFieldUserValue userValue = new SPFieldUserValue(oWeb, oItem["Person or Group Column Name"].ToString());
SPUser userVal = userValue.User;
}
}
ABove code first loads the metadata of the all lists (Not single list, all SharePoint Lists) in that specific SPWeb object. Then it does SPList.Title comparison with metadata of all the lists returned and then it returns the matching list from the SPWeb.Lists collection.