How to make parent node can not selected in treeview ?
If the node is "Parent" , it can not support select,
so I add code
if (drv["isParent"].ToBool())
{
node.Selected = false;
}
But not work? how to fix ?
TreeNode node;
var rows = dv.AsEnumerable().Where(r => r["ParentID"].ToString() == parentid);
foreach (DataRow drv in rows.AsEnumerable())
{
// DataRowView一行
node = new TreeNode();
node.Value = drv["NodeID"].ToString();
node.Text = drv["Name"].ToString();
if (drv["isParent"].ToBool())
{
node.Selected = false;
}
tnc.Add(node);
if (drv["ObjectCode"].ToString() != "0")
{
InitTree(node.ChildNodes, node.Value);
}
}
if (drv["isParent"].ToBool())
{
node.SelectAction = TreeNodeSelectAction.None;
}
Related
I'm trying to populate a TreeView with data from a DataGridView, but I can not.
The DataGridView is with the following information:
TreeView must be like below:
OBS.: I created a TreeView manually to try to explain how I want it to be.
I tried to do like this:
public void CarregaTreeView() {
string pai = "";
string filho = "";
string noPrincipal = "";
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
noPrincipal = dgv.Rows[0].Cells["COD_PAI"].Value.ToString();
foreach (DataGridViewRow row in dgv.Rows) {
pai = (string)row.Cells[0].Value;
filho = (string)row.Cells[3].Value;
if (dict.ContainsKey(pai)) {
dict[pai].Add(filho);
}
else {
dict.Add(pai, new List<string>());
dict[pai].Add(filho);
}
}
//adicionar nó principal
TreeNode objTopNode = new TreeNode(noPrincipal + " - DESCRICAO - [QTDE]");
tv.Nodes.Add(objTopNode);
objTopNode.Tag = noPrincipal;
MontaTreeView(dict, objTopNode);
}
private void MontaTreeView(Dictionary<string, List<string>> dict, TreeNode objparentNode) {
foreach (var kvp in dict) {
objcurrentNode = new TreeNode(kvp.Key + " - DESCRICAO - [QTDE]");
objparentNode.Nodes.Add(objcurrentNode);
objcurrentNode.Tag = kvp.Key;
objcurrentNode.Expand();
if (kvp.Key.Contains("T")) {
Dictionary<string, List<string>> dict1 = new Dictionary<string, List<string>>();
dict1.Add(kvp.Key, new List<string>());
dict1[kvp.Key].Add(dict[kvp.Key][0]);
MontaTreeView(dict1, objcurrentNode);
}
}
}
Basically, you need to iterate over your grid view. For each row, find its parent node in the tree, then add the row to the node children.
TreeNode findParent(string txt, TreeNode parent = null)
{
if (parent == null)
parent = treeView1.Nodes[0];
if (parent.Text == txt) return parent;
foreach (TreeNode node in parent.Children)
{
var res = findParent(txt, node); //recursion
if (res != null) return res;
}
return null;
}
foreach (DataGridViewRow row in dataGrid.Rows)
{
TreeNode parent = findParent(row.Cells[2].Value as string);
var newNode = new TreeNode() { Text = row.Cells[0].Value as Text };
if (parent != null)
parent.Children.Add(newNode);
else
treeView1.Nodes.Add(newNode);
}
When I write this code, I get only the parent tag value. I want to get their childnodes value also, please tell me about this.
XmlDocument DOC = new XmlDocument();
DOC.RemoveAll();
DOC.Load("C:\\Users\\DIGITEL EYE SYSTEM\\Desktop\\response.xml");
foreach (XmlNode AllNodes in ParentNode)
{
Project.Name = AllNodes["Name"].InnerText;
if (AllNodes.ChildNodes == DOC.GetElementsByTagName("AppBuilderForms"))
{
// Project.Forms = DOC.GetElementsByTagName("");
// String sb = AllNodes["Forms"].InnerText;
}
else if (AllNodes.ChildNodes==DOC.GetElementsByTagName("CheckMarkObject"))
{
checkmark.Name = AllNodes["Name"].InnerText;
checkmark.Label = AllNodes["Label"].InnerText;
// checkmark.IsChecked = AllNodes["IsChecked"].InnerText;
}
else if (ParentNode == DOC.GetElementsByTagName("DateTimeObject"))
{
DateTime.Name = AllNodes["Name"].InnerText;
DateTime.Label = AllNodes["Label"].InnerText;
}
else if (ParentNode == DOC.GetElementsByTagName("LocationObject"))
{
Location.Name = AllNodes["Name"].InnerText;
Location.Label = AllNodes["Label"].InnerText;
Location.Longitude = AllNodes["Longitude"].InnerText;
Location.Latitude = AllNodes["Latitude"].InnerText;
}
else if (ParentNode==DOC.GetElementsByTagName("SwitchObject"))
{
Switch.Name = AllNodes["Name"].InnerText;
Switch.Label = AllNodes["Label"].InnerText;
// Switch.IsChecked =AllNodes["IsChecked"].InnerText;
}
else if(ParentNode==DOC.GetElementsByTagName("TextViewObject"))
{
TextView.Name = AllNodes["Name"].InnerText;
TextView.Value = AllNodes["Value"].InnerText;
}
else if (ParentNode ==DOC.GetElementsByTagName("TextFieldObject"))
{
TextField.Name = AllNodes["Name"].InnerText;
TextField.Value = AllNodes["Value"].InnerText;
}
else if (ParentNode == DOC.GetElementsByTagName("PhotoPickerObject"))
{
PhotoPicker.Name = AllNodes["Name"].InnerText;
PhotoPicker.Label = AllNodes["Label"].InnerText;
}
else if (ParentNode == DOC.GetElementsByTagName("SpinWheelPickerObject"))
{
SpinWheelPicker.Name = AllNodes["Name"].InnerText;
SpinWheelPicker.Label = AllNodes["Label"].InnerText;
// SpinWheelPicker.Columns = AllNodes["Columns"].InnerText;
}
}
var xdoc = XDocument.Load(#"C:\Users\DIGITEL EYE SYSTEM\Desktop\response.xml");
var allElements = xdoc.Root.Elements();
foreach (string element in allElements)
{
//TODO add logic
}
First we'll load up the xml into a XDocument (needs .Net 3.5),
nothing odd going on here.
Second we'll select the root node and ALL
the elements under the root into a IEnumrable. You can add a filter here in the Elements() method.
Third we'll start iterating over the elements in our IEnumerable and implicitly
cast them to a string, this is a operator in the LINQ to XML lib
that just returns the XElement.Value (so if you think that's more
readable or need the whole Element for some other reason write
that! I.E XElement element in allElements)
Don't know how to do it in XmlDocument, I've totally forgotten, hopefully this might help you in case you'll go down that path (pun intended).
I want to add to my treeview some nodes with childs, but have a problem how to add nodes with for example ToolTipText. I want do it with TreeNodeCollection.
It is possible or how could I change my code?
Here is my code where all nodes are root nodes.
protected void CreateTreeView(TreeNodeCollection parentNode, int parentID, DataTable mytab)
{
foreach (DataRow dta in mytab.Rows)
{
if (Convert.ToInt32(dta["parent_id"]) == parentID)
{
String key = dta["id"].ToString();
String text = dta["host_ip"].ToString();
TreeNode tn = new TreeNode();
tn.Name = dta["id"].ToString();
tn.Text = dta["host_ip"].ToString();
tn.ToolTipText = dta["description"].ToString();
parentNode.Add(tn);
TreeNodeCollection newParentNode = parentNode;
CreateTreeView(newParentNode, Convert.ToInt32(dta["id"]), mytab);
}
}
}
Calling code:
CreateTreeView(treeView1.Nodes, 0, dt);
If someone had with this problem here is an example:
void add_tooltiptext(DataTable mytab)
{
try
{
foreach (DataRow nodes in mytab.Rows)
{
TreeNode[] found = treeView1.Nodes.Find(nodes["id"].ToString(), true);
for (int i = 0; i < found.Length; i++)
{
treeView1.SelectedNode = found[i];
treeView1.SelectedNode.ToolTipText = nodes["description"].ToString();
}
}
}
catch
{ }
}
Is there a way I can keep the text of a Parent node but remove the link? The treeview parent node is used just as a header, no navigation. Any help would be great. Thanks.
private void BindNodes(string PtID)
{
if (PtID != "")
{
int PatientID = Convert.ToInt32(PtID);
DBConnection dbObj = new DBConnection();
if (Session["Activepatient"] != null)
{
string[] SubChild = new string[4];
SubChild[0] = "Demographics";
SubChild[1] = "Medication Reviews";
SubChild[2] = "Drug Testing & Monitoring";
SubChild[3] = "Other Program";
TreeNode oTrParent = new TreeNode();
//trv_patient.ParentNodeStyle = "None";
//oTrParent.SelectAction.Style.Add("display", "none");
TreeNode oTrSubChild1;
TreeNode oTrSubChild;
for (int i = 0; i < 4; i++)
{
oTrSubChild1 = new TreeNode();
oTrSubChild1.Text = SubChild[i];
if (i == 1)
{
PatientInfoCollection patientCollection = new PatientInfoCollection();
patientCollection = dbObj.GetMedicationReviews(PatientID);
foreach (PatientInfo au in patientCollection)
{
oTrSubChild = new TreeNode();
PatientInfo Patient = new PatientInfo();
oTrSubChild.Text = au.DateRcvd.Value.ToString("MM-dd-yyyy")
oTrSubChild.Target = au.ReviewId.ToString();
oTrSubChild1.ChildNodes.Add(oTrSubChild);
}
oTrSubChild = new TreeNode();
oTrSubChild.Text = "Add Medication Review";
oTrSubChild.Target = "New";
oTrSubChild1.ChildNodes.Add(oTrSubChild);
}
trv_patient.Nodes.Add(oTrSubChild1);
}
}
}
}
If temp is such node whose text you want to be plain text and not link then use code below.
TreeNode temp = new TreeNode("text");
temp.SelectAction = TreeNodeSelectAction.None;
treeView1.Nodes.Add(temp);
This is what your looking for. You have to set the SelectAction of the parent node TreeNode to TreeNodeSelectAction.None. I even show how to do it with the child too.
ASP.NET
<asp:TreeView
ID="MyTreeView"
ShowCheckBoxes="Parent,Leaf,All"
runat="server"
ShowLines="true"
ShowExpandCollapse="true">
</asp:TreeView>
C#
//Make A Parent Node
var Parent = new TreeNode();
Parent.Text = "Parent 1";
// Make the parent nodes not be hyperlinks but plain text
Parent.SelectAction = TreeNodeSelectAction.None;
//You can do the same with a child node like so
var Child = new TreeNode();
Child.Text = "Child 1";
// Make the child nodes not be hyperlinks but plain text
Child.SelectAction = TreeNodeSelectAction.None;
//Add the child node to the parent node
Parent.ChildNodes.Add(Child);
//Finally add the parent node with children to the treeview
MyTreeView.Nodes.Add(Parent);
I'm not sure if I understand what you want. Assuming that it's WinForms and that you just want to disable the ability to select the root node in a TreeView you could just handle the BeforeSelect event of the TreeView and then have the following code:
if (e.Node.Parent == null)
e.Cancel = true;
TreeNode root = new TreeNode("Root");
root.SelectAction = TreeNodeSelectAction.None;
I have a String List with items like this
"Root"
"Root/Item1"
"Root/Item2"
"Root/Item3/SubItem1"
"Root/Item3/SubItem2"
"Root/Item4/SubItem1"
"AnotherRoot"
How do I transfer this stringlist into a treeview ?
You can split each item into it's substrings. Then via recursion look for each item, if the parent exists add to it, and if the parent doesn't exists create it.
If you can't see how to do it, i`ll post you a sample code
Sample Code
public void AddItem(TreeView treeControl, TreeNode parent, string item)
{
TreeNodeCollection nodesRef = (parent != null) ? parent.Nodes : treeControl.Nodes;
string currentNodeName;
if (-1 == item.IndexOf('/')) currentNodeName = item;
else currentNodeName = item.Substring(0, item.IndexOf('/'));
if (nodesRef.ContainsKey(currentNodeName))
{
AddItem(treeControl, nodesRef[currentNodeName], item.Substring(currentNodeName.Length+1));
}
else
{
TreeNode newItem = nodesRef.Add(currentNodeName, currentNodeName);
if (item.Length > currentNodeName.Length)
{
AddItem(treeControl, newItem, item.Substring(item.IndexOf('/', currentNodeName.Length) + 1));
}
}
}
And the caller example:
string[] stringArr = {
"Root",
"Root/Item1",
"Root/Item2",
"Root/Item3/SubItem1",
"Root/Item3/SubItem2",
"Root/Item4/SubItem1",
"AnotherRoot"
};
foreach (string item in stringArr)
{
AddItem(treeView1, null, item);
}
One way is to iterate the items split the item and push them on a list and if the parent doesn't match pop an item from the list until the stack is empty or you have a match.
You can use this code:
private void button1_Click(object sender, EventArgs e) {
List<String> paths = new List<String> {
"Root", "Root/Item1", "Root/Item2", "Root/Item3/SubItem1",
"Root/Item3/SubItem2", "Root/Item4/SubItem1", "AnotherRoot"
};
List<TreeNode> nodeCollection = new List<TreeNode>();
foreach (var path in paths) {
AddPath(nodeCollection, path);
}
treeView1.Nodes.Clear();
treeView1.Nodes.AddRange(nodeCollection.ToArray());
}
public void AddPath(List<TreeNode> collection, String path) {
LinkedList<String> pathToBeAdded = new LinkedList<String>(path.Split(new String[] { #"/" }, StringSplitOptions.RemoveEmptyEntries));
if (pathToBeAdded.Count == 0) {
return;
}
String rootPath = pathToBeAdded.First.Value;
TreeNode root = collection.FirstOrDefault(n => n.Text.Equals(rootPath));
if (root == null) {
root = new TreeNode(rootPath);
collection.Add(root);
}
pathToBeAdded.RemoveFirst();
AddPath(root, pathToBeAdded);
}
public void AddPath(TreeNode rootNode, LinkedList<String> pathToBeAdded) {
if (pathToBeAdded.Count == 0) {
return;
}
String part = pathToBeAdded.First.Value;
TreeNode subNode = null;
if (!rootNode.Nodes.ContainsKey(part)) {
subNode = rootNode.Nodes.Add(part, part);
} else {
subNode = rootNode.Nodes[part];
}
pathToBeAdded.RemoveFirst();
AddPath(subNode, pathToBeAdded);
}
Hope this helps.
Ricardo Lacerda Castelo Branco