C#中Treeview控件学习

 如果程序界面的TreeView控件需要很多节点,如上百个,可以将节点的内容放入数据库或XML文件,然后动态加载数据库或XML文件中的数据,注意数据库或XML文件中的数据之间的逻辑关系。treeview中的加载、删除、和搜索都可以采用递归处理

1、利用递归将数据库(TestPartJob)中的数据加载到TreeView控件中的节点

public List GetAreaByParentId(string pid)
{
   List list = new List();
   string sql = "select Id,Description from DicRegion where ParentId=@pid";
   SqlParameter[] pms = new SqlParameter[]{ 
   new SqlParameter("@pid",SqlDbType.VarChar,6){Value = pid}
   };
   using (SqlDataReader reader = SqlHelper.ExecuteReader(sql,CommandType.Text,pms))
   {
       if (reader.HasRows)
       {
           while (reader.Read())
           {
               TblDicRegion model = new TblDicRegion();
               model.Id= reader.GetString(0);
               model.Description = reader.GetString(1);
               list.Add(model);
            }
        }
    }
    return list;
}
private void LoadData(TreeNodeCollection treeNodeCollection, string pid)
{
    //根据父ParentId查询Id和Description
    List list = GetAreaByParentId(pid);
    //变量每个省市数据
    for (int i = 0; i < list.Count; i++)
    {
        //将每条数据加载到TreeView上
        TreeNode node = treeNodeCollection.Add(list[i].Description);
        node.Tag = list[i].Id;
        //开始递归调用
        LoadData(node.Nodes, list[i].Id);//递归
    }
}

private void btnLoad_Click(object sender, EventArgs e)
{
    string Pid = "12".Trim();
    LoadData(treeView1.Nodes, Pid);       
}

2、TreeView节点被选中的删除操作(传智播客视频代码)

namespace _02模拟三层.DAL
{

    /// 
    /// 操作TblArea表的数据访问层类
    /// 
    public class TblAreaDal
    {
        public List GetAreaByParentId(int pid)
        {
            List list = new List();
            string sql = "select AreaId,AreaName from TblArea where AreaPid=@pid";
            using (SqlDataReader reader = SqlHelper.ExecuteReader(sql, System.Data.CommandType.Text, new SqlParameter("@pid", System.Data.SqlDbType.Int) { Value = pid }))
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        TblArea model = new TblArea();
                        model.AreaID = reader.GetInt32(0);
                        model.AreaName = reader.GetString(1);
                        list.Add(model);
                    }
                }
            }
            return list;
        }


        //根据areaId删除一条记录
        public int DeleteByAreaId(int areaId)
        {
            string sql = "delete from TblArea where AreaId=@id";
            return SqlHelper.ExecuteNonQuery(sql, System.Data.CommandType.Text, new SqlParameter("@id", System.Data.SqlDbType.Int) { Value = areaId });
        }
    }
}

 

namespace ThreeTierStructureLoginTreeViewLoad.BLL
{
    public class DicRegionBll
    {
        DicRegionDal dal = new DicRegionDal();
        public List GetIdByParentId(string pid)
        {
            DicRegionDal objDicRegionDal = new DicRegionDal();
            return objDicRegionDal.ReadFromDicRegion(pid);
        }
        
        public int DeleteById(string id)
        {
            return dal.DeleteById(id);
        }
        //递归删除
        public void DeleteByIdFromDicRegion(string id)
        {
            List list = GetIdByParentId(id);//查询该Id的所有子ID
            for (int i = 0; i < list.Count; i++)
            {
                DeleteByIdFromDicRegion(list[i].Id);  //递归调用自己 
            }
            //2.删除自己
            DeleteById(id);

        }
    }
}

 

private void btnDelete_Click(object sender, EventArgs e)
{
    //1.判断是否有选中节点
    if (treeView1.SelectedNode != null)
    {
        //2.删除该选中节点(递归),数据库中删除
        DeleteByAreaIdRecursive(treeView1.SelectedNode.Tag.ToString());

        //3.从界面上删除该节点
        treeView1.SelectedNode.Remove();
    }
    else
    {
        MessageBox.Show("请选择节点!");
    }
}

3、利用递归搜索TreeView中指定节点,并对该节点进行操作

//查询TreeView控件中名为内丘县的子节点
private void btnSelect_Click(object sender, EventArgs e)
{
    foreach (TreeNode node in this.treeView1.Nodes)
    {
        if (node.Text == "内丘县")
        {
           node.BackColor = Color.Black;
           node.ForeColor = Color.Red;
        }
        SearchNode(node);
    }
}
private void SearchNode(TreeNode tnode)//递归搜索指定名称节点
{
   foreach (TreeNode node in tnode.Nodes)
   {
      if (node.Text == "内丘县")
      {
          node.BackColor = Color.Red;
          node.ForeColor = Color.Yellow;
          node.Parent.Expand();//被选中的父节点展开,定位到需要搜索的节点
       }
    }    
 }

4、对TreeView控件中的子节点添加鼠标右击菜单,先在界面中添加一个contextMenuStrip控件,在contextMenuStrip控件中编译右击显示的内容,将TreeView控件的contextMenuStrip属性与contextMenuStrip控件关联,利用treeView1_NodeMouseClick事件,判断是否是鼠标右键按下,则进行下一步操作

 private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
 {
    if (e.Button != MouseButtons.Right)//如果鼠标左键按下
    {
       return;      
    }

    if (e.Node==null)
    {
         return;   
    }
    //选中根节点不显示右击菜单
    if (e.Node.Parent == null)//如果选中节点无父节点
    {
        this.contextMenuStrip1.Enabled =false;
        this.contextMenuStrip1.Visible = false;
        return;     
    }
    else
    {
        this.contextMenuStrip1.Enabled = Enabled;
    }
    if (this.treeView1.SelectedNode !=null)
    {
        this.treeView1.ContextMenuStrip = contextMenuStrip1;    
    }
               
            
}

 

TreeView节点鼠标右击菜单点击事件

private void cmsDelete_Click(object sender, EventArgs e)
{
    MessageBox.Show("删除");
    treeView1.SelectedNode.Remove();
}

private void cmsLoad_Click(object sender, EventArgs e)
{
    MessageBox.Show("加载");
}

private void cmsUpdate_Click(object sender, EventArgs e)
{
    int r = this.treeView1.GetNodeCount(true); //检索节点的数量,参数为true检索所有节点的数量,参数为false检索父节点的数量 
          
}

 

你可能感兴趣的:(C#)