TreeView控件之我见
今天做了个项目用到了TreeView的几个功能,现总结如下:
(一)添加各级节点:
private void BindData()
{//页面加载时的数据
treeView1.Nodes.Clear();
CommonHelper.AreaHelper areaHelper = new CommonHelper.AreaHelper();
DataTable dt = areaHelper.GetAllCity();
for (int i = 0; i < dt.Rows.Count; i++)
{
//--------------------添加市-------------------------
TreeNode TN = new TreeNode();
TN.ImageIndex = 0;
TN.SelectedImageIndex = 0;
TN.Text = dt.Rows[i]["AreaName"].ToString();
TN.Tag = dt.Rows[i]["AreaID"].ToString();
//--------------------添加县--------------------------
DataTable dt1 = areaHelper.GetCountry(Int32.Parse(dt.Rows[i]["AreaID"].ToString()));
for (int j = 0; j < dt1.Rows.Count; j++)
{
TreeNode TNC = new TreeNode();
TNC.ImageIndex = 1;
TNC.SelectedImageIndex = 1;
TNC.Text = dt1.Rows[j]["AreaName"].ToString();
TNC.Tag = dt1.Rows[j]["AreaID"].ToString();
//-----------------添加区------------------------------
DataTable dt2 = areaHelper.GetArea(Int32.Parse(dt1.Rows[j]["AreaID"].ToString()));
for (int k = 0; k < dt2.Rows.Count; k++)
{
TreeNode TNCC = new TreeNode();
TNCC.ImageIndex = 2;
TNCC.SelectedImageIndex = 2;
TNCC.Text = dt2.Rows[k]["AreaName"].ToString();
TNCC.Tag = dt2.Rows[k]["AreaID"].ToString();
TNC.Nodes.Add(TNCC);
}
TN.Nodes.Add(TNC);
}
treeView1.Nodes.Add(TN);
}
}
效果如图:
(二)遍历TreeView所有节点
public List<TreeNode> GetNode(TreeNodeCollection tc)
{//遍历Treeview所有节点
foreach (TreeNode TNode in tc)
{
tag.Add(TNode);
GetNode(TNode.Nodes);
}
return tag;
}
(三)鼠标右键节点被选中、鼠标双击可改变节点标签内容
private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
this.treeView1.SelectedNode.BeginEdit();
}
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.treeView1.SelectedNode = treeView1.GetNodeAt(e.X,e.Y);
}
}
(四)鼠标右键功能
private void treeView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{//鼠标事件右键功能
if (e.Button == MouseButtons.Right)
{
ContextMenu menu = new ContextMenu();
Point ClickPoint = new Point(e.X, e.Y);
TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
if (CurrentNode == null)
return;
Point ScreenPoint = treeView1.PointToScreen(ClickPoint);
Point FormPoint = this.PointToClient(ScreenPoint);
menu.MenuItems.Clear();
menu.MenuItems.Add("添加根节点");
menu.MenuItems[0].Click += new EventHandler(Option1_Click);
menu.MenuItems.Add("添加子级");
menu.MenuItems[1].Click += new EventHandler(Option2_Click);
menu.MenuItems.Add("删除此节点");
menu.MenuItems[2].Click += new EventHandler(Option3_Click);
menu.Show(this, FormPoint);
}
}
效果如下图: