Hi I am using sharepoint 2010 and am creating a tree view in a webpart to display items from a document library. This code isn't working for me, its displaying everything in the same web...
I would like to be able to specify which document library to use.
Also it puts in duplicate nodes in, so if I go to editpage, it adds a duplicate, if I leave edit mode it adds another duplicate.
Can anyone help?
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.IO;
namespace VisualWebPartProject1.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SPWeb thisWeb = null;
TreeNode node;
using (thisWeb = SPContext.Current.Web)
{
//Add the Web's title as the display text for the tree node, and add the URL as the NavigateUri.
node = new TreeNode(thisWeb.Title, null, null, thisWeb.Url, "_self");
//The Visual Web Part has a treeview control called siteStructure.
siteStructure.Nodes.Add(node);
//Get a reference to the current node, so child nodes can be added in the correct position.
TreeNode parentNode = node;
//Iterate through the Lists collection of the Web.
/*
foreach (SPListItem item in myList.Items)
{
SPFieldUrlValue data = item["Url"] as SPFieldUrlValue;
// now you have data.Description, data.Url
node = new TreeNode(Path.GetFileName(data.Url), null, null, data.Url, "_self");
parentNode.ChildNodes.Add(node);
}
*/
foreach (SPList list in thisWeb.Lists)
{
if (!list.Hidden)
{
node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
parentNode.ChildNodes.Add(node);
}
}
foreach (SPWeb childWeb in thisWeb.Webs)
{
//Call our own helper function for adding each child Web to the tree.
addWebs(childWeb, parentNode);
childWeb.Dispose();
}
siteStructure.CollapseAll();
}
}
void addWebs(SPWeb web, TreeNode parentNode)
{
TreeNode node;
node = new TreeNode(web.Title, null, null, web.Url, "_self");
parentNode.ChildNodes.Add(node);
parentNode = node;
foreach (SPList list in web.Lists)
{
if (!list.Hidden)
{
node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
parentNode.ChildNodes.Add(node);
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call the addWebs() function from itself (i.e. recursively)
//to add all child Webs until there are no more to add.
addWebs(childWeb, parentNode);
childWeb.Dispose();
}
}
}
}
Try adding this before your using statement:
If(node.Nodes.Count == 0) { // The rest of your code here }
Add WebProperties to your WebPart to be able to configure for example the Library which you would like to use instead a hardcoded one. In this Property you could specify the Lists Name and read it to load this list.
Also to avoid multiple inserts on edit, etc. please add your code inside the Page_Load Event inside
if (!Page.IsPostBack)
{
Your code goes here...
}
This avoids the execution of your code everytime you load or even postback the page and this causes that you add each time a new node to your tree.
Related
Hey guys new to C# and I am trying to setup a GUI, all I want the GUI to do is have a simple file explorer with a CheckedListBox to represent selected files.
I can get the CheckedListBox to show up and click on files but I'm not sure how to continue from here, most tutorials stop here, or go too advanced with tree view and other things that seem unnecessary for what I am trying to do.
Here is my code:
Any help is appreciated and if you guys could point me in the right direction that would be awesome.
EDIT:
To rephrase my question:
I want the user to select files through the CheckedListBox (user input stops here), and for those selected files to be put in a list that my code can manipulate.
Not sure how to accomplish this after my first foreach loop (which adds all files in the selected directory to the CheckedListBox for user selection).
The second foreach loop is an attempt at this, manipulating the files so that they output their filenames after being selected. However no Messagebox shows up and I assume that their is a disconnect between the user selecting files and the codes attempt at manipulating said files.
Second Edit:
I think I figured it out I made a second button and from here it looks like I can manipulate the chosen files however I want.
Currently the code is working the way I would expect it to work.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace SelectFiles
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.CheckOnClick = true;
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
checkedListBox1.Items.Clear();
string[] files = Directory.GetFiles(fbd.SelectedPath);
foreach (string file in files)
{
checkedListBox1.Items.Add(file);
}
}
private void button2_Click_1(object sender, EventArgs e)
{
List<string> list_all_excelfiles = new List<string>();
foreach (string item in checkedListBox1.CheckedItems)
{
list_all_excelfiles.Add(item);
MessageBox.Show(Path.GetFileName(item));
}
}
}
}
First i advice you to assign Value member and Display member for each item.
Display Member will be visible to user
Value Member will we use in code
To do this first create simple custom class
public class Int_String
{
public int _int { get; set; }
public string _string { get; set; }
}
Be careful because get; set; part is important to be there since if not code will not work
Now what you need to do is create list of items with custom class like this
class YourForm : Form
{
List<Int_String> myList = new List<Int_String>(); //Create list of our custom class
public YourForm()
{
PopulateMyList();
}
private void PopulateMyList()
{
//Here read from database or get data somehow and populate our list like this
//I will populate it manually but you do it in foreach loop
myList.Add(new Int_String { _int = 0, _string = "First Item" });
myList.Add(new Int_String { _int = 1, _string = "Second Item" });
myList.Add(new Int_String { _int = 2, _string = "Third Item" });
}
}
After that you need to assign this list to your checkedListBox which you will do like this:
public YourForm()
{
PopulateMyList();
checkedListBox1.DataSource = myList;
checkedListBox1.DisplayMember = "_string";
checkedListBox1.ValueMember = "_int";
}
And now when you can manipulate with checked items like this:
for(int i = 0; i < checkedListBox1.Items.Count; i++)
{
if(checkedListBox1.Items[i].CheckedState == CheckState.Checked)
{
int itemValueMember = (checkedListBox1.Items[i] as Int_String)._int;
int itemDisplayMember = (checkedListBox1.Items[i] as Int_String)._string;
//Use these two vars for whatever you need
}
}
TWO IMPORTANT TIPS:
I am not sure for this one since i am writing all this from head but i think that visual studio will not show you that there is DisplayMember or ValueMember for checkedBox component BUT also it will not show error. Reason is that they have hidden in intentionally for idk what reason but it will work.
You are able to assign Display and Value member to a lot of components in winforms BUT for some reason checkedListBox is specific. It is specific because you MUST first assign DataSource to it and then tell it checkedListBox.DisplayMember = "_string" ...... For new guy you will ask why it is important. Simple answer is create custom list for test and add 10k items inside it and then first declare datasource and after it Display and Value member. Test how long form will need to load (get out of freeze state). After that do everything same but first declare Display and Value member and then assign datasource and test again. I am telling this from head without testing but before when i needed about 5k rows with 1st solution it took me about 30 sec and second < 1 sec. If you want to know more about it google it but for now this is pretty much info for you.
I am working on a windows phone app. I want to copy children of one canvas to other canvas. I can do it with the following code but the problem is I have to remove it from one canvas first. Code is:
private void add_template_Click(object sender, RoutedEventArgs e)
{
var childrenList = Template_canvas1.Children.Cast<UIElement>().ToArray();
root.Children.Clear();
foreach (var c in childrenList)
{
Template_canvas1.Children.Remove(c);
root.Children.Add(c);
}
}
I want to keep these elements on both the canvas. Is there another way?
Instead of trying to add the same Template_canvas1.Children to the root canvas, first make a copy of those Children and then add the copy to the root canvas.
public static T CloneXaml<T>(T source)
{
string xaml = XamlWriter.Save(source);
StringReader sr = new StringReader(xaml);
XmlReader xr = XmlReader.Create(sr);
return (T)XamlReader.Load(xr);
}
Then change your loop to:
foreach (var c in childrenList)
{
var copy = CloneXaml(c);
root.Children.Add(copy);
}
I haven't tested this code, so you may have to modify it a bit, but it should put you in the right direction.
Alternatively, you can probably use the code below which is copied from Dr Herbie's answer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using System.Reflection;
using Windows.UI.Xaml.Controls;
namespace UIElementClone {
public static class UIElementExtensions {
public static T DeepClone<T>(this T source) where T : UIElement {
T result; // Get the type
Type type = source.GetType(); // Create an instance
result = Activator.CreateInstance(type) as T;
CopyProperties<T>(source, result, type);
DeepCopyChildren<T>(source, result);
return result;
}
private static void DeepCopyChildren<T>(T source, T result) where T : UIElement {
// Deep copy children.
Panel sourcePanel = source as Panel;
if (sourcePanel != null) {
Panel resultPanel = result as Panel;
if (resultPanel != null) {
foreach (UIElement child in sourcePanel.Children) {
// RECURSION!
UIElement childClone = DeepClone(child);
resultPanel.Children.Add(childClone);
}
}
}
}
private static void CopyProperties<T>(T source, T result, Type type) where T : UIElement {
// Copy all properties.
IEnumerable<PropertyInfo> properties = type.GetRuntimeProperties();
foreach (var property in properties) {
if (property.Name != "Name") { // do not copy names or we cannot add the clone to the same parent as the original.
if ((property.CanWrite) && (property.CanRead)) {
object sourceProperty = property.GetValue(source);
UIElement element = sourceProperty as UIElement;
if (element != null) {
UIElement propertyClone = element.DeepClone();
property.SetValue(result, propertyClone);
}
else {
try {
property.SetValue(result, sourceProperty);
}
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
}
}
}
}
If none of these worked for you, I'm afraid you'd have to implement your own serializer. It looks like David Poll implemented a decent serlizer, so have a look. Using his serlizer is as simple as using the XamlWriter, then you can use the XamlReader:
public static T CloneXaml<T>(T source)
{
UiXamlSerializer uxs = new UiXamlSerializer();
string xaml = uxs.Serialize(source);
StringReader sr = new StringReader(xaml);
XmlReader xr = XmlReader.Create(sr);
return (T)XamlReader.Load(xr);
}
To get this functionality, download his Slab library, go to the "Binaries" folder and copy all the dlls that start with "SLaB.Utilities.Xaml.Serializer" to your project. There might be some other dlls required as dependency. He has example solution in the library if you like to look at the code an learn.
Without a good Minimal, Complete, and Verifiable example that shows clearly what you've tried, with a precise description of what exactly you're trying to achieve, it's impossible to know for sure what the best answer would be.
That said, given that WPF already knows how to "clone" elements in a sense, through the use of data templates, your question really sounds a lot like an XY Problem to me. That is, you only think you need to literally clone the elements already in your visual tree, when in fact what you should be doing is defining a view model that represents the data to be displayed for the element(s) to be "cloned", define a single data template that uses XAML to describe the visual elements that will display the data in the view model, and then simply apply the template as necessary wherever you want the visual elements to be "cloned".
I.e. they won't really be cloned. Instead, WPF will automatically populate a whole new sub-tree of visual elements exactly as you want them to be. Since the template allows you to completely define all aspects, there is no issue related to e.g. trying to get the event subscriptions hooked up, setting up bindings correctly, etc.
In your specific example (vague though it is), it sounds like you most likely want to use an ItemsControl element, in which the ItemsPanel is a Canvas object. You would then define a DataTemplate that represents a single item in the ItemsPanel; this template would be referenced either implicitly by setting its DataType property, or explicitly by setting the ItemsControl.ItemTemplate property. Then, instead of cloning anything, you just create an ItemsControl when you want a copy of your visual for the data.
New answer after user's feedback that it is not working on Windows Phone
Complete final Windows Phone App can be downloaded here.
There are some API differences, for example instead of pinfo.SetMethod property we have to use pinfo.GetSetMethod() etc.
Secondly, I was unknowingly didn't check for Name property which must not be copied as otherwise we would be making another instance with same name.
Third, I posted for simple case of simple controls like Button, TextBox, Rectangle etc which do not contain children. If that is the case you have to go for recursive deep cloning to clone children too. As children could have more children and so on.
foreach (UIElement oldElem in Canvas1.Children)
{
try
{
Type t = oldElem.GetType();
UIElement newElem = (UIElement)Activator.CreateInstance(t);
PropertyInfo[] info = t.GetProperties();
int i = 0;
foreach (PropertyInfo pinfo in info)
{
if (pinfo.Name == "Name") continue;
try
{
if (pinfo.GetSetMethod() != null) // avoid read-only properties
pinfo.SetValue(newElem, pinfo.GetValue(oldElem, null),null);
}
catch (Exception ex)
{
Debug.WriteLine((++i).ToString() + " : " + pinfo.ToString());
}
}
Canvas.SetLeft(newElem, Canvas.GetLeft((oldElem)));
Canvas.SetTop(newElem, Canvas.GetTop((oldElem)));
Canvas2.Children.Add(newElem);
}
catch (Exception ex)
{
}
}
And if you are going for truly deep cloning then replace code in outer try block above with a simpler:
foreach (UIElement oldElem in Canvas1.Children)
{
try
{
UIElement newElem = oldElem.DeepClone();
Canvas2.Children.Add(newElem);
Canvas.SetLeft(newElem, Canvas.GetLeft(oldElem));
Canvas.SetTop(newElem, Canvas.GetTop(oldElem));
}
catch (Exception ex){ }
}
Old answer based on WPF only
Don't know about windows phone but in WPF this creates a fresh element and puts it in exactly same place in another canvas. Check if it fits your needs, else I will update it again.
foreach (UIElement oldElem in Canvas1.Children)
{
Type t = oldElem.GetType();
UIElement newElem = (UIElement)Activator.CreateInstance(t);
PropertyInfo[] info = t.GetProperties();
int i = 0;
foreach (PropertyInfo pinfo in info)
{
try
{
if (pinfo.SetMethod != null) // avoid read-only properties
pinfo.SetValue(newElem, pinfo.GetValue(oldElem));
}
catch (Exception ex)
{
Debug.WriteLine((++i).ToString() + " : " + pinfo.ToString());
}
}
Canvas.SetLeft(newElem, Canvas.GetLeft((oldElem)));
Canvas.SetTop(newElem, Canvas.GetTop((oldElem)));
Canvas.SetRight(newElem, Canvas.GetRight((oldElem)));
Canvas.SetBottom(newElem, Canvas.GetBottom((oldElem)));
Canvas2.Children.Add(newElem);
}
I have a TreeView and an associated ImageList. What are the steps to add images to the Parent and child nodes ?
All the nodes are being added from the code. Nothing is done from the Design.
public void fill_tree()
{
host_listbox_new.Items.Clear();
foreach (KeyValuePair<string, host_config> hlitem in host_list)
{
string sitem = hlitem.Key;
if (host_list[sitem].sessionOptions == null)
host_list[sitem].sessionOptions = new SessionOptions();
host_list[sitem].sessionOptions.Protocol = Protocol.Sftp;
host_list[sitem].sessionOptions.HostName = host_list[sitem].ip;
host_list[sitem].sessionOptions.UserName = host_list[sitem].username;
host_list[sitem].sessionOptions.Password = host_list[sitem].password;
host_list[sitem].sessionOptions.PortNumber = Convert.ToInt32(host_list[sitem].port);
//host_list[sitem].sessionOptions.SshHostKeyFingerprint = host_list[sitem].rsa;
if (treeView1.SelectedNode != null)
{
treeView1.SelectedNode.Nodes.Add(hlitem.Key.ToString());
}
else
{
treeView1.Nodes[0].Nodes.Add(hlitem.Key.ToString());
}
}
}
private void Parent_Load(object sender, EventArgs e)
{
read_process_config();
read_host_config();
host_listbox.Items.Clear();
treeView1.BeginUpdate();
treeView1.Nodes.Add("Servers");
fill_tree();
treeView1.EndUpdate();
treeView1.ExpandAll();
connect_server_bttn.Enabled = false;
}
i want to add items i.e child nodes to Server Parent node each of them having one image before them ( green image if hlitem.Value.connected is true. red image if hlitem.Value.connected is false)
But i have no idea about treeview or imagelist.
Can anyone help me about the whole thing?
The Add command returns a reference to the new Node. You can use it to style the Node.
Change your code to this:
if (treeView1.SelectedNode != null)
{
TreeNode tn =treeView1.SelectedNode.Nodes.Add(hlitem.Key.ToString());
tn.ImageIndex = yourIndex;
}
else
{
TreeNode tn =treeView1.Nodes[0].Nodes.Add(hlitem.Key.ToString());
tn.ImageIndex = yourIndex;
}
Or whatever logic you need to set the index.
If you need the parent node's index you could write:
tn.ImageIndex = tn.Parent.ImageIndex;
You may also want ot check out the other formats of the Add method. Some let you include the ImageIndex directly. You can also include the SelectedIndex; especially if you don't want that you should include it to prevent the Tree using its default SelectedIndex!
This will set the node to show the 2nd image, whether selected or not:
TreeNode tn =treeView1.Nodes[0].Nodes.Add(sitem, sitem, 1,1 );
Since you can't set a property of an object before you have created it, you can't set the Child nodes when you create the parent node. Instead you can use a simple function to do the changes:
void copyImgIndexToChildren(TreeNode tn)
{
if (tn.Nodes.Count > 0)
foreach (TreeNode cn in tn.Nodes) cn.ImageIndex = tn.ImageIndex;
}
void copyImgIndexToAllChildren(TreeNode tn)
{
if (tn.Nodes.Count > 0)
foreach (TreeNode cn in tn.Nodes)
{
cn.ImageIndex = tn.ImageIndex;
copyImgIndexToAllChildren(cn);
}
}
The first method changes the direct ChildNodes only , the 2nd recursively changes all levels below the starting node.
BTW: Is there a reason to use hlitem.Key.ToString() in your code instead of sitem?
This is an example of using XPathNavigator from Microsoft.
using System;
using System.Xml;
using System.Xml.XPath;
// http://support.microsoft.com/kb/308343
namespace q308343 {
class Class1 {
static void Main(string[] args) {
XPathNavigator nav;
XPathDocument docNav;
docNav = new XPathDocument(#"Books.Xml");
nav = docNav.CreateNavigator();
nav.MoveToRoot();
//Move to the first child node (comment field).
nav.MoveToFirstChild();
do {
//Find the first element.
if (nav.NodeType == XPathNodeType.Element) {
//Determine whether children exist.
if (nav.HasChildren == true) {
//Move to the first child.
nav.MoveToFirstChild();
//Loop through all of the children.
do {
//Display the data.
Console.Write("The XML string for this child ");
Console.WriteLine("is '{0}'", nav.Value);
//Check for attributes.
if (nav.HasAttributes == true) {
Console.WriteLine("This node has attributes");
}
} while (nav.MoveToNext());
}
}
} while (nav.MoveToNext());
//Pause.
Console.ReadLine();
}
}
}
I think this code has a bug that it doesn't execute MoveToParent() to go up to one level when there is no elements to show.
nav.MoveToFirstChild();
//Loop through all of the children.
do {
....
} while (nav.MoveToNext());
nav.MoveToParent(); <-- This seems to be missing.
However, when I compile/execute this example, it works fine with and without nav.MoveToParent().
Is MoveToParent()/MoveToFirstChild() pair necessary with XPathNavigator? Is it OK not to use MoveToParent() because the second execution of MoveToNext() works as MoveToParent() when the first execution of MoveToNext() returns false?
In this code, after we go through all of the children of the root node, there is no more work to be done, there can't be more than one root node. So there is no need to MoveToParent(), we can just exit. Which is exactly what the code does.
I need to construct a huge treeview from a composite database table with Grouping.
Grouping is, what we see in SQL Server Management Studio Express. After a Database node, some fixed folders are shown (like, Database Diagrams, Tables, Views, Synonyms, Programmability and Security) and children are grouped in those folders.
Up to this point I have used AfterSelect event and handler to achieve this.
But the problem with AfterSelect is, before selecting the node, the viewer is not able to know whether there is any child available. This is because, the expandable plus sign is not visible.
I want to use BeforeExpand. But the problem with BeforeExpand is, it works if the children are already populated. In that case, when I click groups, nothing happens.
How to solve this?
So codes/web-link will be appreciated.
What I usually do is to add a "dummy child node" wherever there may be children that should be loaded in a lazy manner. This will make the parent have the plus sign, and then you can add code to the AfterExpand event where you do the following:
Check if there are are exactly one child, and if that child is the dummy node (you can use the Tag property to identify the dummy node)
If the dummy node is found, launch a search to get the children and add them to the parent node, finish it off by removing the dummy node.
I typically give the dummy node a text like "Loading data. Please wait..." or so, so that the user gets some info on what is going on.
Update
I put together a simple example:
public class TreeViewSample : Form
{
private TreeView _treeView;
public TreeViewSample()
{
this._treeView = new System.Windows.Forms.TreeView();
this._treeView.Location = new System.Drawing.Point(12, 12);
this._treeView.Size = new System.Drawing.Size(200, 400);
this._treeView.AfterExpand +=
new TreeViewEventHandler(TreeView_AfterExpand);
this.ClientSize = new System.Drawing.Size(224, 424);
this.Controls.Add(this._treeView);
this.Text = "TreeView Lazy Load Sample";
InitializeTreeView();
}
void TreeView_AfterExpand(object sender, TreeViewEventArgs e)
{
if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Tag == "dummy")
{
// this node has not yet been populated, launch a thread
// to get the data
ThreadPool.QueueUserWorkItem(state =>
{
IEnumerable<SomeClass> childItems = GetData();
// load the data into the tree view (on the UI thread)
_treeView.BeginInvoke((Action)delegate
{
PopulateChildren(e.Node, childItems);
});
});
}
}
private void PopulateChildren(TreeNode parent, IEnumerable<SomeClass> childItems)
{
TreeNode child;
TreeNode dummy;
TreeNode originalDummyItem = parent.Nodes[0];
foreach (var item in childItems)
{
child = new TreeNode(item.Text);
dummy = new TreeNode("Loading. Please wait...");
dummy.Tag = "dummy";
child.Nodes.Add(dummy);
parent.Nodes.Add(child);
}
originalDummyItem.Remove();
}
private IEnumerable<SomeClass> GetData()
{
// simulate that this takes some time
Thread.Sleep(500);
return new List<SomeClass>
{
new SomeClass{Text = "One"},
new SomeClass{Text = "Two"},
new SomeClass{Text = "Three"}
};
}
private void InitializeTreeView()
{
TreeNode rootNode = new TreeNode("Root");
TreeNode dummyNode = new TreeNode("Loading. Please wait...");
dummyNode.Tag = "dummy";
rootNode.Nodes.Add(dummyNode);
_treeView.Nodes.Add(rootNode);
}
}
public class SomeClass
{
public string Text { get; set; }
}
It's standard behaviour for a tree to show a "+" in front of every folder/group, and the plus dissapears when clicked on if it's found to have no children, this saves the expensive "do you have children" check.
Alternatively you can provide this information if you have a cheap way of determining if a node has children. This question provides more information.