Programmatically creating a treeview in sharepoint based on a column - c#

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();
}

Related

Accessing resources attached to list items in SharePoint

I'm accessing a list of calendar items on a SharePoint2013 site like so:
public ListItemCollection GetListByTitle(string title)
{
ClientContext context = new ClientContext(_site);
List list = context.Web.Lists.GetByTitle(title);
ListItemCollection listItems = list.GetItems(new CamlQuery()); // Empty CamlQuery to return all items in list
context.Load(listItems);
context.ExecuteQuery();
return listItems;
}
Then I'm passing that ListItemCollection to another method which will map some of the item's properties to a custom model
public List<CustomModel>GetListOfCustomModel(ListItemCollection listItems)
{
List<CustomModel> customModelList = new List<CustomModel>();
foreach(ListItem i in listItems)
{
FieldUserValue contact = (FieldUserValue)i.FieldValues["Contact"];
string s = (string)(contact.LookupValue);
string t = (string)i.FieldValues["Title"];
DateTime start = (DateTime)i.FieldValues["EventDate"];
// etc.
}
}
All of the "in-built" properties are easy to get, but I can't figure out how to access the resources the company has created and attached to these items.
E.g. each calendar item has a "Room" resource attached. I understand this is "meta data" but surely I should be able to access it somehow? It must be linked to the item I just don't know where to look. When I do a SharePoint list view for every column in the list I can see the "room" resource is generated as a link with reference to the resource.
Or am I going to end up viewing the text response from viewing my LISTALL page in a web request and parse the room out using good old fashioned string manipulation?!
I'd been looking at this for a couple of days, and I found a piece of code that translates a ListItemCollection to a DataTable
This code handled Microsoft.SharePoint.Client.FieldLookupValue, Microsoft.SharePoint.Client.FieldUserValue and Microsoft.SharePoint.Client.FieldUserValue[] but when I was looking at my Excel output I saw a Microsoft.SharePoint.Client.FieldLookupValue[]
Debugged the code again and drilled down into this instance of a FieldLookupValue[] called Facilities which, lo and behold, has the room and all other "Resources" in there.
SHORT ANSWER: Don't look for resources, look for FACILITIES
Here's some code I lifted from another answer site that cycles through ListItemCollection and transposes info to a DataTable but amended to show Id as well as value for FieldUserValue arrays and, more importantly, do the same for FieldLookupValue arrays:
public DataTable GetDataTableFromListItemCollection(ListItemCollection listItems)
{
DataTable dt = new DataTable();
foreach (var field in listItems[0].FieldValues.Keys)
{
dt.Columns.Add(field);
}
foreach (var item in listItems)
{
DataRow dr = dt.NewRow();
foreach (var obj in item.FieldValues)
{
if (obj.Value != null)
{
string key = obj.Key;
string type = obj.Value.GetType().FullName;
if (type == "Microsoft.SharePoint.Client.FieldLookupValue")
{
dr[obj.Key] = ((FieldLookupValue)obj.Value).LookupValue;
}
else if (type == "Microsoft.SharePoint.Client.FieldUserValue")
{
dr[obj.Key] = ((FieldUserValue)obj.Value).LookupValue;
}
else if (type == "Microsoft.SharePoint.Client.FieldUserValue[]")
{
FieldUserValue[] multValue = (FieldUserValue[])obj.Value;
foreach (FieldUserValue fieldUserValue in multValue)
{
dr[obj.Key] += "&" + fieldUserValue.LookupId + "=" + fieldUserValue.LookupValue;
}
}
else if (type == "Microsoft.SharePoint.Client.FieldLookupValue[]")
{
FieldLookupValue[] multValue = (FieldLookupValue[])obj.Value;
foreach (FieldLookupValue fieldLookupValue in multValue)
{
dr[obj.Key] += "&" + fieldLookupValue.LookupId + "=" + fieldLookupValue.LookupValue;
}
}
else if (type == "System.DateTime")
{
if (obj.Value.ToString().Length > 0)
{
var date = obj.Value.ToString().Split(' ');
if (date[0].Length > 0)
{
dr[obj.Key] = date[0];
}
}
}
else
{
dr[obj.Key] = obj.Value;
}
}
else
{
dr[obj.Key] = null;
}
}
dt.Rows.Add(dr);
}
return dt;
}
https://social.technet.microsoft.com/Forums/en-US/4bf89ee1-50a1-4c21-9ef9-51bd4d2ae155/convert-listitemcollection-to-datatable-without-looping-through-all-list-items-using-csom?forum=SP2016

Iterating through a List to show in TreeView

I have four lists that I am trying to get the contents to show up in a TreeView on my Form.
My current problem is that only the last item in each list is showing up in the view.
I am sure it has something to do with how I am iterating through the list but I am pretty stuck on how to get each individual list item to show up in the tree.
My tree structure is:
Dog
Husky
huskylist
Chiwawa
chiwawlist
Cat
Siamese
siameselist
Tabby
tabbylist
My code for the Form where the tree view is:
public partial class Form1 : Form
{
private Model m_modelObj;
public Form1(Model modelObj)
{
InitializeComponent();
m_modelObj = modelObj;
List<Tabby> tabbyList = m_modelObj.TabbyList;
List<Siamese> siameseList = m_modelObj.SiameseList;
List<Husky> huskyList = m_modelObj.HuskyList;
List<Chiwawa> chiwawaList = m_modelObj.ChiwawaList;
//tree code
//add husky list
TreeNode node8 = null;
foreach (var item in huskyList)
{
node8 = new TreeNode(item.name);
}
TreeNode[] husky = new TreeNode[] { node8 };
//add chiwawa list
TreeNode node9 = null;
foreach (var item in chiwawaList)
{
node9 = new TreeNode(item.name);
}
TreeNode[] chiwawa = new TreeNode[] { node9 };
//dog breed
TreeNode node2 = new TreeNode("Husky", husky);
TreeNode node3 = new TreeNode("Chiwawa", chiwawa);
TreeNode[] dog = new TreeNode[] { node2, node3 };
//dog parent
TreeNode treeNode = new TreeNode("Dogs", dog);
treeView1.Nodes.Add(treeNode);
//add tabby list
TreeNode nodes = null;
foreach (var item in tabbyList)
{
nodes = new TreeNode(item.name);
}
TreeNode[] tabby = new TreeNode[] { nodes };
//add siamese list
TreeNode node7 = null;
foreach (var item in siameseList)
{
node7 = new TreeNode(item.name);
}
TreeNode[] siamese = new TreeNode[] { node7 };
//cat breed
TreeNode node4 = new TreeNode("Siamese", siamese);
TreeNode node5 = new TreeNode("Tabby", tabby);
TreeNode[] cat = new TreeNode[] { node4, node5 };
//cat parent
treeNode = new TreeNode("Cats", cat);
treeView1.Nodes.Add(treeNode);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void addDetailsBtn_Click(object sender, EventArgs e)
{
string animalType = comboBoxAnimalType.SelectedItem.ToString();
this.Hide();
PetInfoForm aPetInfoForm = new PetInfoForm(animalType, m_modelObj);
aPetInfoForm.Closed += (s, args) => this.Close();
aPetInfoForm.Show();
}
}
Create Object and Dynamic array in c# Refer here
TreeView Basic to understand Refer here
when you are creating the sub nodes you are overwrite the instance. you should maintain the nodes in a array.
//tree code
//add husky list
List<TreeNode> node8 = new List<TreeNode>();
foreach (var item in huskyList)
{
node8.Add(new TreeNode(item.name));
}
TreeNode[] husky = node8.ToArray();
//add chiwawa list
List<TreeNode> node9 = new List<TreeNode>();
foreach (var item in chiwawaList)
{
node9.Add(new TreeNode(item.name));
}
TreeNode[] chiwawa = node9.ToArray();
//dog breed
TreeNode node2 = new TreeNode("Husky", husky);
TreeNode node3 = new TreeNode("Chiwawa", chiwawa);
TreeNode[] dog = new TreeNode[] { node2, node3 };
//dog parent
TreeNode treeNode = new TreeNode("Dogs", dog);
treeView1.Nodes.Add(treeNode);
//add tabby list
List<TreeNode> nodes = new List<TreeNode>();
foreach (var item in tabbyList)
{
nodes.Add(new TreeNode(item.name));
}
TreeNode[] tabby =nodes.ToArray();
//add siamese list
List<TreeNode> node7 = new List<TreeNode>();
foreach (var item in siameseList)
{
node7.Add(new TreeNode(item.name));
}
TreeNode[] siamese = node7.ToArray();
//cat breed
TreeNode node4 = new TreeNode("Siamese", siamese);
TreeNode node5 = new TreeNode("Tabby", tabby);
TreeNode[] cat = new TreeNode[] { node4, node5 };
//cat parent
treeNode = new TreeNode("Cats", cat);
treeView1.Nodes.Add(treeNode);
Or
Using LINQ you can create the tree like this
// Code Using Linq
TreeNode husky = new TreeNode("Husky", huskyList.Select(x => new TreeNode(x.name)).ToArray());
TreeNode chiwawa = new TreeNode("Chiwawa", chiwawaList.Select(x => new TreeNode(x.name)).ToArray());
TreeNode Siamese = new TreeNode("Siamese", siameseList.Select(x => new TreeNode(x.name)).ToArray());
TreeNode Tabby = new TreeNode("Tabby", tabbyList.Select(x => new TreeNode(x.name)).ToArray());
//parent nodes
treeView1.Nodes.AddRange(new[] {
new TreeNode("Dog", new TreeNode[] { husky, chiwawa }),
new TreeNode("Cat", new TreeNode[] { Siamese, Tabby })
});

Treeview not adding properly as child

I have the code below to expand the tree node to add childeren to its parents , till the nth level.
Issue : The child is added to the first level always, instead it should have been added till the nth level, to its appropriate parent.
Code below:
public void Populate_Node(Object sender, TreeNodeEventArgs e)
{
// Authenticating
TreeProvider cmsTree = new TreeProvider(MembershipContext.AuthenticatedUser);
//selecting the expanding node
var node = cmsTree.SelectSingleNode(SiteContext.CurrentSiteName, "/Level1-2ndItem", "en-US");
CMS.DocumentEngine.TreeNodeCollection myChildren = node.AllChildren;
//Making array of child treenodes of selected node
IEnumerable<CMS.DocumentEngine.TreeNode> TreeNodes = myChildren.AsEnumerable<CMS.DocumentEngine.TreeNode>();
foreach (var tree in myChildren)
{
System.Web.UI.WebControls.TreeNode ParenTreeNode = new System.Web.UI.WebControls.TreeNode();
ParenTreeNode.Text = tree.NodeID.ToString() + ". " + SiteContext.CurrentSiteName;
ParenTreeNode.Value = tree.NodeID.ToString();
AddExpandedNodes(ParenTreeNode);
}
}
private void AddExpandedNodes(System.Web.UI.WebControls.TreeNode TreeNode)
{
CMS.DocumentEngine.TreeProvider cmsTree = new CMS.DocumentEngine.TreeProvider(CMS.Membership.MembershipContext.AuthenticatedUser);
var node = cmsTree.SelectSingleNode(CMS.SiteProvider.SiteContext.CurrentSiteName, "/", "en-US");
CMS.DocumentEngine.TreeNodeCollection myChildren = node.AllChildren;
IEnumerable<CMS.DocumentEngine.TreeNode> childTreeNodes = myChildren.AsEnumerable<CMS.DocumentEngine.TreeNode>().Where(x => x.NodeParentID == Convert.ToInt32(TreeNode.Value));
foreach (var childTree in childTreeNodes)
{
System.Web.UI.WebControls.TreeNode ChildNode = new System.Web.UI.WebControls.TreeNode();
ChildNode.Text = childTree.NodeID.ToString() + ". " + childTree.DocumentName.ToString();
ChildNode.Value = childTree.NodeID.ToString();
ChildNode.ChildNodes.Add(ChildNode);
AddExpandedNodes(ChildNode);
tvContentTree.Nodes.Add(ChildNode);
}
}

add SPListItem to a SPListItemCollection

I have the following code for load a list from sharepoint site.
ALl is working well exept a SPList item to SPListItemCollection.
private void Data_load()
{
DataTable dt = new DataTable();
string currentName = SPContext.Current.Web.CurrentUser.Name;
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Editor'/><Value Type='Person or Group'>" + currentName + "</Value></Eq></Where>";
using (SPSite site = new SPSite("http://spdev-6/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList lists = web.GetList("Lists/Advertisements");
SPListItemCollection items = lists.GetItems(query);
if (items.Count > 0)
{
DataRow dr=null;
SPListItemCollection ITEM = null;
foreach(SPListItem item in items)
{
string A = item["Approval Status"].ToString();
if(A== "2")
{
ITEM.Add(item);
}
}
if(dt.Rows.Count==0)
lbldata.Text = "No data to show";
// dt = items.GetDataTable();
}
else
lbldata.Text = "No data to show";
GridViewD.DataSource = dt;
GridViewD.DataBind();
HttpContext.Current.Session["Advertisement"] = dt;
}
}
}
Now in if(A== "2"){ ITEM.Add(item); }
I want to add SPListItem to a SPListItemCollection. Please help.
You are trying to add an item into null because your ITEM is null. I don't know what error you are getting ( your don't write it) but you must initialize your collection:
if (items.Count > 0)
{
DataRow dr=null;
SPListItemCollection ITEM = ... //
foreach(SPListItem item in items)
{
string A = item["Approval Status"].ToString();
if(A== "2")
{
SPListItem myItem = ITEM.Add();
// set your item's fields here
// Use indexers on this object for each field to assign specific values, and then call the Update method on the item to effect changes in the database.
myItem["Approval Status"] = item["Approval Status"];
...
myItem.Update();
}
}
if(dt.Rows.Count==0)
lbldata.Text = "No data to show";
// dt = items.GetDataTable();
}

How to get Sharepoint List using 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();
}
}

Categories