How to get Sharepoint List using c# - c#

How to get fields values from a particular list item.In my case i want to get all form fileds of Workplan list.Actually i want to get Workplan all list item and insert to sharepoint 2013 associated database.
I try the following code.
string strUrl = "http://example.com/default.aspx";
using (SPSite site = new SPSite(strUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[52];
SPQuery myquery = new SPQuery();
myquery.Query = "";
SPListItemCollection items = list.GetItems(myquery);
foreach (SPListItem item in items)
{
if (item != null)
{
var Name = item.ListItems.Fields.List;
Console.WriteLine("Name is :" + Name);
}
}
}
}

This is the easiest way I can think of using Server Object Model:
string strUrl = "http://example.com";
using(SPSite oSite = new SPSite(strUrl))
{
using(SPWeb oWeb = oSite.OpenWeb())
{
SPList list = oWeb.Lists["Workplan"];
foreach(SPField field in list.Fields)
{
Console.WriteLine(field.Title);
}
}
}
Btw, as for your site-URL "http://example.com/default.aspx" it is enough to do it like "http://example.com".
For more information on Sharepoint I recommend using this site in the future.

using (SPSite site = new SPSite("URL")
{
using (SPWeb web = site.OpenWeb("sitecollection/subsite"))
{
//to get specific list type
string listUrl = "/sites/sitecollection/subsite/Lists/Announcements";
SPList list = web.GetList(listUrl);
Console.WriteLine("List URL: {0}", list.RootFolder.ServerRelativeUrl);
}
}
//To get all lists from spweb use this:
SPSite oSiteCollection = SPContext.Current.Site;
using(SPWebCollection collWebs = oSiteCollection.AllWebs)
{
foreach (SPWeb oWebsite in collWebs)
{
SPListCollection collSiteLists = oWebsite.Lists;
foreach (SPList oList in collSiteLists)
{
//get your each list here
}
oWebsite.Dispose();
}
}

Related

Retrieve a SharePoint list data into a datatable in JSON format using asp.net web API

I am trying to get data from a SharePoint list using asp.net web API MVC application, then load it to a datatable and finally give that as API output as JSON format.
I have tried to get the data from a SharePoint list, but SharePoint gives null as a result.
I am expecting the data to load to my data table and API should give that data as JSON output.
Your Question is not clear. Still, I Tried.
This is the code which i used in my console application.
public static SPListItemCollection GetCollection()
{
string listName = 'Your List Name';
string queryStr = "<Where><Eq><FieldRef Name='Title''/><Value Type='Text'>" + YourValue + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>";
SPListItemCollection oCollection = GetListItemCollectionByQuery(listName, queryStr);
return oCollection;
}
public static SPListItemCollection GetListItemCollectionByQuery(string ListName, string queryText)
{
SPListItemCollection spListItemCollection = null;
string webUrl = Your Site URL;
try
{
using (SPSite oSPsite = new SPSite(webUrl))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
string listName = ListName;
SPList spList = oSPWeb.Lists[listName];
if (spList != null)
{
SPQuery spQuery = new SPQuery();
spQuery.Query = queryText;
spListItemCollection = spList.GetItems(spQuery);
}
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
return spListItemCollection;
}
Also, you need to check this Get DataTable
I hope it may help :)

How to retrieve list items from SharePoint 2013

At work we had to move from SharePoint 2010 to 2013 and my code for retrieving list items doesn't work anymore. Here is my code for SP 2010:
com.mycompany.intranet.Lists listService = new com.mycompany.intranet.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = "url";
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
string listName = cbxMailDistributionList.SelectedValue.ToString();
string viewName = "";
string rowLimit = "0";
System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
viewFields.InnerXml = "<FieldRef Name='Title' />";
System.Xml.XmlNode nodeListItems =
listService.GetListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, null);
xmlDoc.LoadXml(nodeListItems.InnerXml);
xlNodeList rows = xmlDoc.GetElementsByTagName("z:row");
List<string> recipients = new List<string>();
foreach (XmlNode attribute in rows)
{
if(attribute.Attributes["ows_Title"].Value == null){}
else {
if (recipients.Contains(attribute.Attributes["ows_Title"].Value)){}
else {
recipients.Add(attribute.Attributes["ows_Title"].Value);
}
}
}
recipients.Sort();
distributionList = recipients;
Can you please help me to get it working with a SharePoint 2013 list again?
URL has already been updated but i get the following error: https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=DE-DE&k=k(EHNullReference);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.0);k(DevLang-csharp)&rd=true
But the list has no empty fields.
listName
is the ID of the list element.
Please help.
Thanks in advance!
Finally it works again with this code:
List<string> recipients = new List<string>();
string siteURL = #"myurl/";
ClientContext cc = new ClientContext(siteURL);
cc.Credentials = System.Net.CredentialCache.DefaultCredentials;
Web web = cc.Web;
List list = web.Lists.GetById(new Guid(cbxMailDistributionList.SelectedValue.ToString()));
CamlQuery caml = new CamlQuery();
ListItemCollection items = list.GetItems(caml);
cc.Load<List>(list);
cc.Load<ListItemCollection>(items);
cc.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
if(item.FieldValues["Title"] == null) { }
else
{
if (recipients.Contains(item.FieldValues["Title"].ToString())) { }
else
{
recipients.Add(item.FieldValues["Title"].ToString());
}
}
}
recipients.Sort();
distributionList = recipients;
}
else
{
distributionList = null;
}
New day, new luck. Sorry for the prematurely posting of this question. I should have slept on it for a night. ;)
BR

Updating SPFile properties using SPFile.Update()

I'm trying to update SPFile properties.
Here is my code:
using (SPSite oSite = new SPSite(sFileURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
oFile = oWeb.GetFile(sFileURL);
foreach (XmlNode xNode in oXmlDoc.FirstChild.ChildNodes)
{
oFile.Item.Properties[xNode.Name] = xNode.InnerText;
string itemmm =oFile.Item.Properties[xNode.Name].ToString();
}
oFile.Update();
oWeb.AllowUnsafeUpdates = false;
}
}
The problem is that when I check the file properties in SharePoint I don't see the changes I have made.
I was trying to add AllowUnsafeUpdates = true but it didn't solve the problem.
What else can I do?
In fact, you don't modify SPFile instance, but the associated SPItem. Hence calling SPFile.Update() does nothing. It's better to work with the SPItem instance directly:
SPItem item = oFile.Item;
item.Properties[xNode.Name] = xNode.InnerText;
item.Update();
Also, AllowUnsafeUpdates property is not relevant to your situation. Do not alter it.
Your code is lacking all checks which is to be done before actual update.
using (SPSite oSite = new SPSite(sFileURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
SPFile oFile = oWeb.GetFile(sFileURL);
if (oFile == null)
{
return false;
}
SPListItem item = oFile.GetListItem();
if (item.File.Level == SPFileLevel.Checkout)
{
item.File.UndoCheckOut();
}
if (item.File.Level != SPFileLevel.Checkout)
{
item.File.CheckOut();
}
item["Your Column name"] = "Value";
item.SystemUpdate(false);
item.File.CheckIn("SystemCheckedin");
item.File.Publish("SystemPublished");
oWeb.AllowUnsafeUpdates = false;
}
}

Only Remove SPGroups that Contain a specific Character

I need to remove groups from a SharePoint site that contain an underscore in the name. I need something like the below code, but I am unable to use .Contains on the collGroups.
Any idea how I can do this?
using (SPSite oSite = new SPSite(spsite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPGroupCollection collGroups = oWeb.SiteGroups;
if(collGroups.Contains("_")) //this doens't work, but I need something like this
{
group.Delete();
}
}
}
For future reference: here is what I ended up writing, thanks to gunr2171 for pointing me in the right direction!
using (SPSite oSite = new SPSite(spsite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
var result = (from g in oWeb.Groups.OfType<SPGroup>()
where g.Name.Contains("_")
select g).ToList();
foreach (SPGroup group in result)
{
SPGroupCollection collGroups = oWeb.SiteGroups;
collGroups.Remove(group.Name);
Console.WriteLine("Removed " + group.Name);
}
Console.WriteLine("Process Complete!");
}

Programmatically creating a treeview in sharepoint based on a column

I have to develop a web part for SharePoint that reads a list and creates a tree view.
The tree view has to be organized as follows:
The root (or roots) is to be created by a choice field which represents a category, for instance Drinks,
the child nodes are the name of the rows that contain that category, the tree view has to be created programmatically.
List:
Title(string) Category(Choice)
Coke Drinks
Beer Drinks
Fish Food
Chips Food
Would produce this:
Drinks
Coke
Beer
Food
Fish
Chips
code I have so far
TreeView treeView;
TreeNode rootNode;
TreeNode childNode;
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
// render the control
base.RenderContents(writer);
}
protected override void CreateChildControls()
{
List<TreeNode> items = new List<TreeNode>();
base.CreateChildControls();
// get the current site
using (SPSite Site = new SPSite(SPContext.Current.Site.Url + "/UberWiki"))
{
using (SPWeb currentWeb = Site.OpenWeb())
{
// set the tree view properties
SPList list = currentWeb.Lists["Pages"];
SPFieldChoice field = (SPFieldChoice)list.Fields["Categories"];
foreach (string str in field.Choices)
{
treeView = new System.Web.UI.WebControls.TreeView();
rootNode = new System.Web.UI.WebControls.TreeNode(str);
treeView.Nodes.Add(rootNode);
foreach (SPListItem rows in list.Items)
{
childNode = new System.Web.UI.WebControls.TreeNode(rows.Title);
treeView.Nodes.Add(childNode);
}
}
}
this.Controls.Add(treeView);
base.CreateChildControls();
}
}
Found the solution:
using (SPSite Site = new SPSite(SPContext.Current.Site.Url + "/UberWiki"))
{
using (SPWeb currentWeb = Site.OpenWeb())
{
SPList list = currentWeb.Lists["Pages"];
SPFieldChoice field = (SPFieldChoice)list.Fields["Categories"];
treeView = new System.Web.UI.WebControls.TreeView();
foreach (string str in field.Choices)
{
treeNode = new System.Web.UI.WebControls.TreeNode(str);
foreach (SPListItem rows in list.Items)
{
SPFieldMultiChoiceValue multiChoice = new SPFieldMultiChoiceValue(Convert.ToString(rows["Wiki Categories"]));
string input = multiChoice.ToString();
//remove the ;# that comes with the multiple choiches
string cleanString = input.Replace(";#", "");
if (cleanString == str)
{
string PageNameWithExt = rows.Name;
childNode = new System.Web.UI.WebControls.TreeNode(PageNameWithExt);
treeNode.ChildNodes.Add(childNode);
}
}
treeView.Nodes.Add(treeNode);
}
}
}
this.Controls.Add(treeView);
base.CreateChildControls();
}
Another solution without the need to clean the multi choice string values
using (SPSite Site = new SPSite(SPContext.Current.Site.Url + "/UberWiki"))
{
using (SPWeb currentWeb = Site.OpenWeb())
{
// set the tree view properties
SPList list = currentWeb.GetList(currentWeb.Url+"/Lists/Pages");
SPFieldChoice field = (SPFieldChoice)list.Fields["Categories"];
treeView = new System.Web.UI.WebControls.TreeView();
// Add root nodes
foreach (string str in field.Choices)
{
rootNode = new System.Web.UI.WebControls.TreeNode(str);
treeView.Nodes.Add(rootNode);
}
// Add child nodes
foreach (SPListItem rows in list.Items)
{
childNode = new System.Web.UI.WebControls.TreeNode(rows["Title"].ToString());
treeView.FindNode(rows["Categories"].ToString()).ChildNodes.Add(childNode);
}
}
this.Controls.Add(treeView);
base.CreateChildControls();
}

Categories