當前選中項:TreeView.SelectedNode
增加頂級節點:TreeView.Nodes.Add("Key", "Text")
增加同級節點:TreeView.SelectedNode.Parent.Nodes.Add("Key", "Text")
增加子節點:TreeView.SelectedNode.Nodes.Add("Key", "Text")
全部展開:TreeView.ExpandAll()
全部收攏:TreeView.CollapseAll()
重新設置TreeView
數據庫表結構為: ID 類型名稱 父級ID
代碼如下:
private void loadTreeView()
{
this.貨品類別TableAdapter1.Fill(superCargoDataSet1.貨品類別);
DataTable table = superCargoDataSet1.貨品類別;
DataRow[] row = table.Select("父級ID=0");
foreach (DataRow r in row)
{
TreeNode node = 貨品類別TreeView.Nodes.Add(r["ID"].ToString(), r["類型名稱"].ToString());
recursionShow(node, r["ID"].ToString());
}
}
private void recursionShow(TreeNode nodes, string id)
{
DataTable table = superCargoDataSet1.貨品類別;
DataRow[] row = table.Select("父級ID=" + id);
if (row != null)
{
foreach (DataRow r in row)
{
TreeNode node = nodes.Nodes.Add(r["ID"].ToString(), r["類型名稱"].ToString());
recursionShow(node, r["ID"].ToString());
}
}
}
刪除選中節點和其子結點,同時刪除數據庫中相應記錄
數據庫表結構為: ID 類型名稱 父級ID
代碼如下:
private void 刪除ToolStripButton_Click(object sender, EventArgs e)
{
if (貨品類別TreeView.SelectedNode != null)
{
DataRow[] rowChildren = superCargoDataSet1.貨品類別.Select("ID=" + 貨品類別TreeView.SelectedNode.Name.ToString());
if (rowChildren != null)
{
foreach (DataRow row in rowChildren)
{
delete節點(row["ID"].ToString());
row.Delete();
}
}
貨品類別TreeView.SelectedNode.Remove();
}
}
private void delete節點(string id)
{
DataRow[] rowChildren = superCargoDataSet1.貨品類別.Select("父級ID=" + id);
if (rowChildren != null)
{
foreach (DataRow row in rowChildren)
{
delete節點(row["ID"].ToString());
row.Delete();
}
}
}
TreeView右鍵選中
代碼如下:
private void treeView左側_MouseDown( object sender , MouseEventArgs e )
{
if( e.Button == MouseButtons.Right )
{
TreeNode node = treeView左側.GetNodeAt (e.X , e.Y);
if( node != null )//右鍵未選中節點,不改變當前選中的節點。VS2005如此。
{
this.treeView左側.SelectedNode = node;
}
}
}