The idea was to create a navigation webpart which will display dataor links from a list.
Further, I also had a requirenment to change the navigation data according to the selected tab in top navigation. To achive this , i just slected the list name from a custom toolpane of the webpart and then the below webpart will display data from a different list.
Note : I am using a Link type list named "All Programs".
Below is the Code to create a tree view bind to a list
namespace CustomNavigationWP
{
[Guid("93215435-7b75-49e7-b99f-07e96e50b02f")]
public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
{
TreeView treeView;
TreeNode rootNode;
public WebPart1()
{
}
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
// render the control
base.RenderContents(writer);
}
protected override void CreateChildControls()
{
base.CreateChildControls();
// get the current site
SPSite currentSite = SPContext.Current.Site;
using (SPWeb currentWeb = currentSite.OpenWeb())
{
// set the tree view properties
treeView = new System.Web.UI.WebControls.TreeView();
treeView.ShowLines = true; // show lines
treeView.ExpandDepth = 0; // expand non
SPList list = currentWeb.Lists["All Programs"];
// build the tree
rootNode = new System.Web.UI.WebControls.TreeNode(list.Title, "", "", list.RootFolder.ServerRelativeUrl.ToString(), "");
// loop down the tree
GetFolder(list.RootFolder, rootNode, list);
// add the root node to tree view
treeView.Nodes.Add(rootNode);
}
this.Controls.Add(treeView);
base.CreateChildControls();
}
public void GetFolder(SPFolder folder, TreeNode rootNode, SPList list)
{
// create a new node
TreeNode newNode = new System.Web.UI.WebControls.TreeNode(folder.Name, "", "~/_layouts/images/itdl.gif", folder.ServerRelativeUrl.ToString(), "");
try
{
// don't add the forms folder
if (folder.Name != "Link")
{
// loop through all child folders
foreach (SPFolder childFolder in folder.SubFolders)
{
// don't add the forms folder
if (childFolder.Name != "Link")
{
TreeNode trn = new System.Web.UI.WebControls.TreeNode(childFolder.Name, "", "", childFolder.ServerRelativeUrl.ToString(), "");
newNode = GetItems(childFolder, trn);
// add the new node to the tree
rootNode.ChildNodes.Add(newNode);
}
}
}
}
catch { }
}
public TreeNode GetItems(SPFolder folder, TreeNode node)
{
//Get Items from childFolder
SPQuery qry = new SPQuery();
qry.Folder = folder;
SPWeb web = null;
web = folder.ParentWeb;
SPListItemCollection ic = web.Lists[folder.ParentListId].GetItems(qry);
foreach (SPListItem subitem in ic)
{
if (subitem.Folder != null) //Is Subfolder
{
// create a new node for a subfolder and add items to it
TreeNode childNode = new System.Web.UI.WebControls.TreeNode(subitem.Folder.Name);
node.ChildNodes.Add(GetItems(subitem.Folder, childNode));
}
if (subitem.Folder == null)
{
TreeNode trn1 = new System.Web.UI.WebControls.TreeNode(subitem["Title0"].ToString());
node.ChildNodes.Add(trn1);
}
}
return node;
}
}
}
No comments:
Post a Comment