The c sharp TreeView control USES code

  • 2020-05-05 11:50:22
  • OfStack

Currently selected: TreeView.SelectedNode
Add a top-level node: TreeView.Nodes.Add ("Key", "Text")
Peer nodes are added: TreeView SelectedNode. Parent. Nodes. Add (" Key ", "Text")
Add child nodes: TreeView SelectedNode. Nodes. Add (" Key ", "Text")
All expanded: TreeView.ExpandAll()
All closed: TreeView.CollapseAll()
Reset TreeView
The database table structure is ID type name parent ID
 
private void loadTreeView() 
{ 
this. Product categories TableAdapter1.Fill(superCargoDataSet1. Product categories ); 
DataTable table = superCargoDataSet1. Product categories ; 
DataRow[] row = table.Select(" The parent ID=0"); 
foreach (DataRow r in row) 
{ 
TreeNode node =  Product categories TreeView.Nodes.Add(r["ID"].ToString(), r[" Type the name "].ToString()); 
recursionShow(node, r["ID"].ToString()); 
} 
} 
private void recursionShow(TreeNode nodes, string id) 
{ 
DataTable table = superCargoDataSet1. Product categories ; 
DataRow[] row = table.Select(" The parent ID=" + id); 
if (row != null) 
{ 
foreach (DataRow r in row) 
{ 
TreeNode node = nodes.Nodes.Add(r["ID"].ToString(), r[" Type the name "].ToString()); 
recursionShow(node, r["ID"].ToString()); 
} 
} 
} 

Delete the selected node and its children, as well as the corresponding record
in the database The database table structure is: ID type name parent ID
 
private void  delete ToolStripButton_Click(object sender, EventArgs e) 
{ 
if ( Product categories TreeView.SelectedNode != null) 
{ 
DataRow[] rowChildren = superCargoDataSet1. Product categories .Select("ID=" +  Product categories TreeView.SelectedNode.Name.ToString()); 
if (rowChildren != null) 
{ 
foreach (DataRow row in rowChildren) 
{ 
delete node (row["ID"].ToString()); 
row.Delete(); 
} 
} 
 Product categories TreeView.SelectedNode.Remove(); 
} 
} 
private void delete node (string id) 
{ 
DataRow[] rowChildren = superCargoDataSet1. Product categories .Select(" The parent ID=" + id); 
if (rowChildren != null) 
{ 
foreach (DataRow row in rowChildren) 
{ 
delete node (row["ID"].ToString()); 
row.Delete(); 
} 
} 
} 

TreeView, right click
 
private void treeView On the left side of the _MouseDown( object sender , MouseEventArgs e ) 
{ 
if( e.Button == MouseButtons.Right ) 
{ 
TreeNode node = treeView On the left side of the .GetNodeAt (e.X , e.Y); 
if( node != null )// Right-click an unselected node and do not change the currently selected node. VS2005 The case.  
{ 
this.treeView On the left side of the .SelectedNode = node; 
} 
} 
} 

Related articles: