How to access List Items in a list - sharepoint

I'm trying to display the ListItems in a gridview.
Please help me in finding a way to access the list items.
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
.......
.......
}
}
Please help me in accessing the list item values.

The below code should do the trick, get the full article from msdn here
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
SPListItemCollection collListItems = list.Items;
foreach (SPListItem oListItem in collListItems)
{
string value = SPEncode.HtmlEncode(oListItem["Field1_Name"]);
// do something with value
}
}
}

You may use any of the below:
SPList list;
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
SPQuery query = new SPQuery();
query.ViewFields = "<FieldRef Name='Title'/>";
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
for (int i = 0; i < list.Items.Count; i++ )
{
string title = list.Items[i]["Title"];
}
From the performance point of view, I suggest using the SP Query as then you can specify which fields to fetch and whether or not to fetch any associated metadata with the list items. This results in fewer db calls.
Kind regards,

Use SPDataSource to display list items in a grid view, i.e. create and configure an SPDataSource object and bind it to a SPGridView control.

For displaying items in a gridview (if you don't want to use SPGridView), I would use the GetDataTable method, instead of using a foreach loop as many of the answers do.
if (items.Count > 0)
{
DataTable dt = items.GetDataTable();
GridView1.DataSource = dt;
GridView1.DataBind();
}

Well, I haven't done any sharepoint work, but I believe you can use:
foreach (SPListItem item in list.Items)
or
foreach (SPListItem item in list.GetItems(view)) // or query
or access by index or guid:
SPListItem item = list.Items[10];
SPListItem item = list.Items[guid];

The SPQuery approach as suggested by unknown(yahoo) is the way to go, however you should remember that the default rowlimit of SPQuery is 100:
try
{
using (SPSite site = new SPSite(theURL))
{
SPWeb web = site.OpenWeb();
SPList list = web.Lists["TheNameOfTheList"];
//search each ListItem where the date is after 1/1 2009
SPQuery query = new SPQuery();
//the default is 100, which is less then the expected max
query.RowLimit = 500;
// The U2U CAML Query builder rules :-)
query.Query = "<Where><Gt><FieldRef Name='StartDate' /><Value Type='DateTime'>";
query.Query += "2009-01-01T00:00:00Z</Value></Gt></Where>";
SPListItemCollection resultset = list.GetItems(query);
foreach (SPListItem item in resultset)
{
// do something
}
}
}

If you´re using .NET 3.5 I would recommend using the linq datasource together with the spgridview to bind splistitems to a gridview. Saves you a lot of time.
I have an example of this on my blog.
To display images you have to get the url of the image. Here is an example of that:
SPListItem item = GetItem();
string imagefieldhtml = item["NameOfImageField"].ToString();
ImageFieldValue imagefield = new ImageFieldValue(imagefieldhtml);
var url = imagefield.ImageUrl;
The url variable will now hold the image url.

Ok, I have solved the above issue. In my case I did not need to use the SPEncode.HTML, so I have commented out everything that's not needed. Here is the fixed code if anyone else needs it:
using (SPSite site3 = SPContext.Current.Site)
{
using (SPWeb web2 = site3.OpenWeb())
{
// SPWeb site3 = SPContext.Current.Site.RootWeb;
SPList list2 = web2.Lists["Configuration"];
SPListItemCollection collListItems = list2.Items;
foreach (SPListItem oListItem in list2.Items)
{
//string value = SPEncode.HtmlEncode.ToString(oListItem["List name"]);
string valueListName = oListItem["List name"].ToString();
string valueListURL = oListItem["List URL"].ToString();
}
}
}

Related

Is there a Sharepoint API to get nested directory structure for a particular folder at once within a site?

Is there a Sharepoint API to get entire content of files/folders for a particular folder at once ?
I don't want to use GetFolderByServerRelativePath recursively.
If don't want to use GetFolderByServerRelativePath, you can use CSOM with CAML Query like this:
string password = "pwd";
string account = "user#Tenant.onmicrosoft.com";
var secret = new SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename"))
{
ctx.Credentials = new SharePointOnlineCredentials(account,secret);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle("Documents");
ctx.Load(list);
ctx.ExecuteQuery();
Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/shared%20documents/");
ctx.Load(folder);
ctx.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'>
<Query>
</Query>
</View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (var item in listItems)
{
Console.WriteLine(item.FieldValues["FileRef"].ToString());
}
}
will return all folders/subfolders/files together, hopefully, this is what you need.

How to get list of all document libraries from sharepoint site programatically

I am using below code which gives me both list & document library; but I am trying to get list of only document libraries.
Please help me how to differentiate list & document library programatically
using(SPSite oSite = new SPSite("https://server/site"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPListCollection oLists = oWeb.Lists;
foreach (SPList olist in oLists)
{
Response.Write(olist.Title+"<br>");
}
}
}
See this Post
Try this ways :
using(SPSite oSite = new SPSite("https://server/site"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPListCollection docLibraryColl = oWeb.GetListsOfType(SPBaseType.DocumentLibrary);
foreach (SPList list in docLibraryColl)
{
Response.Write(list.Title+"<br>");
}
}
}
Hope its helps!!
Try something like this
using(SPSite oSite = new SPSite("https://server/site"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPListCollection oLists = oWeb.Lists;
foreach (SPDocumentLibrary olist in oLists.OfType<SPDocumentLibrary>())
{
Response.Write(olist.Title+"<br>");
}
}
}

Safely return all lists in site collection that match criteria

I'm using the following code to get all "Announcement" lists in a Web Applications site collection.
Unfortunately, sometimes the current user does not have permission to that site and the page fails with an exception, even inside the try block.
What would be the right way to do the following safely for all users, where even an anonymous user would just get no results?
static public List<SPListMeta> AllSiteAnnouncementsLists()
{
var returnList = new List<SPListMeta>();
foreach (SPSite oSiteCollection in SPContext.Current.Web.Site.WebApplication.Sites)
{
var collWebs = oSiteCollection.AllWebs;
try
{
foreach (SPWeb oWebsite in collWebs)
{
using (oWebsite)
{
var collSiteLists = oWebsite.GetListsOfType(SPBaseType.GenericList);
returnList.AddRange(from SPList oList in collSiteLists where oList.Title == "Announcements" select new SPListMeta(oList));
}
}
}
catch
{
}
}
return returnList;
}
Try give your code the right permission to execute.
using Microsoft.Sharepoint.Administrator;
SPSecurity.RunWithElevatedPrivileges(delegate(){
// Your source code goes here
});
To get all items of the specific list type from the site collection you have to use SPSiteDataQuery. Each user will get only those items they have permissions.
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
//Ask for all lists created from the announcement template.
query.Lists = "<Lists ServerTemplate=\"104\" />";
// Get the Title field. Define here all you need.
query.ViewFields = "<FieldRef Name=\"Title\" />";
// Set the sort order.
query.Query = "<OrderBy>" +
"<FieldRef Name=\"Title\" />" +
"</OrderBy>";
// Query all Web sites in this site collection.
query.Webs = "<Webs Scope=\"SiteCollection\" />";
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
This is what ended up working for me, though I do not know if it is the best way to do this.
static public List<SPListMeta> AllSiteAnnouncementsLists()
{
var returnList = new List<SPListMeta>();
var collWebs = SPContext.Current.Web.Site.WebApplication.Sites[0].OpenWeb().GetSubwebsForCurrentUser();
if(SPContext.Current.Site.RootWeb.DoesUserHavePermissions(SPBasePermissions.Open))
{
var collSiteLists = SPContext.Current.Site.RootWeb.GetListsOfType(SPBaseType.GenericList);
returnList.AddRange(from SPList oList in collSiteLists
where oList.DoesUserHavePermissions(SPBasePermissions.ViewListItems)
&& oList.BaseTemplate == SPListTemplateType.Announcements
select new SPListMeta(oList));
}
foreach (SPWeb oWebsite in collWebs)
{
returnList.AddRange(WebRecursion.GetListsForCurrentWeb(oWebsite, SPListTemplateType.Announcements));
foreach (SPWeb oSubSite in oWebsite.Webs)
{
returnList.AddRange(WebRecursion.GetListsForCurrentWeb(oSubSite, SPListTemplateType.Announcements));
}
}
return returnList;
}
public static List<SPListMeta> GetListsForCurrentWeb(SPWeb oWebsite, SPListTemplateType type)
{
var returnList = new List<SPListMeta>();
if (oWebsite.DoesUserHavePermissions(SPBasePermissions.Open))
{
using (oWebsite)
{
var collSiteLists = oWebsite.Lists;
returnList.AddRange(from SPList oList in collSiteLists
where oList.DoesUserHavePermissions(SPBasePermissions.ViewListItems)
&& oList.BaseTemplate == type
select new SPListMeta(oList));
}
}
return returnList;
}

Do I really need foreach loop for this?! (foreach probably overkilling)

I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem li in list.items and loop through each item (if li.name==myitemname then assign strguid=li.uniqueid.tostring()
Is there a way not to use foreach loop since I know the name of the item? This will save time to loop throught items.
If you are creating a spquery on your unique item in splistcollection you would be returned only one element which you can obtain without foreach
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList apps = web.GetList(web.Url + "/Lists/MyList");
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='String'>{0}</Value></Eq></Where>", _title);
items = apps.GetItems(query);
if(items.Count > 0)
{
Guid id = items[0].UniqueId;
}
}
}
Works but I have 11 files and they all have the same file name "license.txt" and they are in the same document library. 1 file "license.txt" is under the root document library and other 10 in 10 different folders within a document library. so what if i am looking for the license.txt file that's in Demo folder?
This code works but only finds license.txt under the root.
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
Trying the following and it seems to be working.
query.ViewAttributes = "Scope=\"Recursive\"";
or
query.ViewAttributes = "Scope='RecursiveAll'";

Item count should be 10 but is 0

the items.count should be atlease 10. I have 10 subfolders (Release 1 ..... Release 10) with in this documnent library "Auto Cad" and each subfolder has a file called license.txt. hmmm
Why this is not returning any file(s)?
private void btnGetFileGuid_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("https://www.abc.com/sites/Software"))
{
using (SPWeb web = site.OpenWeb())
{
SPList spList = web.Lists["Auto Cad"];
string fileName = "license.txt";
SPQuery query = new SPQuery();
query.Query="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>" + fileName + "</Value></Eq></Where>";
SPListItemCollection items = spList.GetItems(query);
if (items.Count > 0)
{
Guid id = items[0].UniqueId;
lblGuid.Text = id.ToString();
}
}
}
}
SPQuery only searches a particular folder - to recursively search through subfolders you need to set
SPQuery.ViewAttributes = "Scope=\"Recursive\"";
So your code should be
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
query.Query=".... REST OF YOUR CODE HERE "
query.Query="" + fileName + "";
This line is wrong. This should be CAML query and not name of filename.
You need to make a recursive call use the solution provided in question link provided below
i would recommend use qry.ViewAttributes = "Scope='RecursiveAll'"; to get documents and folders as well
query to get all items in a list including items in the sub folders in sharepoint

Resources