打赏

C# TreeView 控件的综合使用方法

1、概述

    该篇文章开发使用的语言c#,环境visualstudio2010,sql数据库.主要内容包括:

(1)treeView控件添加根节点、子节点的基本方法,节点的删除。

(2)把treeView控件的节点数据保存到SQL数据包括中,把数据库数据表中的数据动态加载到treeView控件中,控件节点的递归删除(指的是递归删除数据表的数据)

2、TreeView控件的基本用法

     为了演示相关方法、属性的用法,通过vs2010创建一个winform项目,在项目中添加一个窗体,其布局如图2-1所示

 

 

图2-1

其中TreeView控件的名称为:treeview1,文本框的名称为:txtNodeName,“添加根节点”按钮的名称为:btnAddRootNode,“添加子节点”按钮的名称为:btnAddSonNode,“删除选中节点”按钮的名称:btnDelete

添加节点、删除节点的代码如下所示:

2.1添加根节点

 1 private void btnAddRootNode_Click(object sender, EventArgs e)
 2   {
 3       //要添加的节点名称为空,即文本框是否为空
 4         if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
 5          {
 6              MessageBox.Show("要添加的节点名称不能为空!");
 7              return;
 8          }
 9             //添加根节点
10             treeView1.Nodes.Add(txtNodeName.Text.Trim());
11            txtNodeName.Text = "";
12   }
添加根节点代码

2.2添加子节点

 1 private void btnAddSonNode_Click(object sender, EventArgs e)
 2    {
 3        //要添加的节点名称为空,即文本框是否为空
 4         if (string.IsNullOrEmpty(txtNodeName.Text.Trim()))
 5          {
 6              MessageBox.Show("要添加的节点名称不能为空!");
 7               return;
 8          }
 9          if(treeView1.SelectedNode==null)
10           {
11              MessageBox.Show("请选择要添加子节点的节点!");
12               return;
13           }               treeView1.SelectedNode.Nodes.Add(txtNodeName.Text.Trim());
14     txtNodeName.Text = "";
15    }
添加子节点代码

2.3删除选中节点

1  private void btnDelete_Click(object sender, EventArgs e)
2   {
3       if (treeView1.SelectedNode == null)
4          {
5               MessageBox.Show("请选择要删除的节点!");
6               return;
7          }
8             treeView1.SelectedNode.Remove();
9   }
删除选中节点代码

3、TreeView控件在树形菜单中的应用

    Treeview在产品类别管理、部门管理等树状多级菜单中的应用,主要包括把树控件中的数据保存到SQL数据表中,把数据表中的数据动态加载到treeview控件中,以及删除控件节点及数据表中的数据。

3.1数据表

create table TreeTest
(
 id int identity(1,1) primary key not null,//节点id
 nodeName nvarchar(50) not null,//节点名称
 parentId int not null//节点父id
)
create Table

3.2把节点数据存储到数据表

    把treeView添加的节点信息存储到数据表,包括根节点、子节点,所用的窗体界面如图2-1所示,控件的名称保持不变,只是执行代码变了。

 1  private void btnAddRootNode_Click (object sender, EventArgs e)
 2   {
 3         if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
 4          {
 5              MessageBox.Show("请填写要添加的节点名称!");
 6               return;
 7          }
 8   string sql = "insert into TreeTest(nodeName,parentId) output inserted.id values"+"("+" "+"'"+ txtNodeName.Text.Trim()+"'"+","+"'"+0+"'"+")";
 9             int id = (int)sqlHelper.ExecuteScalar(sql);
10             TreeNode node1 = new TreeNode();
11             node1.Tag = id;//把自己的id存放在该节点tag对象里
12             node1.Text = txtNodeName.Text.Trim();
13             treeView1.Nodes.Add(node1);
14             txtNodeName.Text = "";
15         }
添加根节点
 1 private void btnAddSonNode_Click (object sender, EventArgs e)
 2    {
 3             int id;
 4             if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
 5             {
 6                 return;
 7             }
 8             if(treeView1.SelectedNode==null)
 9             {
10                 MessageBox.Show("请选择父节点");
11                 return;
12             }
13             id =(int)treeView1.SelectedNode.Tag;//获取父id
14             string sql = "insert into TreeTest(nodeName,parentId) output inserted.id values"+"(" + " " + "'" + txtNodeName.Text.Trim() + "'" + "," + "'" + id + "'" + ")";
15             int id1 = (int)sqlHelper.ExecuteScalar(sql);
16             TreeNode node1 = new TreeNode();
17             node1.Tag = id1;
18             node1.Text = txtNodeName.Text.Trim();
19             treeView1.SelectedNode.Nodes.Add(node1);
20             txtNodeName.Text = "";
21  }
添加子节点

3.3动态加载数据

    把数据表中的数据动态加载到treeView控件中,在treeView所在窗体的load事件中加载,相应的代码如下所示

 1 private void Form3_Load(object sender, EventArgs e)
 2  {      
 3      //加载数据,把数据加载到控件treeview1中   
 4      setTreeView(treeView1, 0);           
 5  }
 6 
 7  //调用的时候parentId以0值开始 setTreeView(treeView1, 0);
 8   private void setTreeView(TreeView tr1,int parentId)
 9  {
10   string sql = "select * from TreeTest where parentId=" + parentId;
11       DataTable ds= sqlHelper.ExecuteDataTable(sql);
12        if (ds.Rows.Count > 0)
13         {
14                int pId = -1;
15              foreach (DataRow row in ds.Rows)
16                {
17                     TreeNode node = new TreeNode();
18                     node.Text = row["nodeName"].ToString();
19                     node.Tag = (int)row["id"];
20                     pId = (int)row["parentId"];
21                     if (pId == 0)
22                     {
23                         //添加根节点
24                         tr1.Nodes.Add(node);
25                     }
26                     else
27                     {
28                         //添加根节点之外的其他节点
29                         RefreshChildNode(tr1,node,pId);
30                     }
31                     //查找以node为父节点的子节点
32                     setTreeView(tr1,(int)node.Tag);
33 
34                 }
35             }
36 
37    }
38 //处理根节点的子节点
39   private void RefreshChildNode(TreeView tr1,TreeNode treeNode, int parentId)
40  {
41          foreach (TreeNode node in tr1.Nodes)
42             {
43                 if((int)node.Tag==parentId)
44                 {
45                     node.Nodes.Add(treeNode);
46                     return;
47                 }else if (node.Nodes.Count > 0)
48                 {
49                     FindChildNode(node, treeNode,  parentId);
50                 }
51             }
52  }
53 
54   //处理根节点的子节点的子节点
55   private void FindChildNode(TreeNode  tNode,TreeNode treeNode, int parentId)
56  {
57          foreach (TreeNode node in tNode.Nodes)
58           {
59                 if ((int)node.Tag == parentId)
60                 {
61                     node.Nodes.Add(treeNode);
62                     return;
63                 }else if (node.Nodes.Count > 0)
64                 {
65                     FindChildNode(node,treeNode,parentId);
66                 }
67 
68             }
69 
70 }
动态加载数据代码

3.4、递归删除节点,这里指的是递归删除节点在数据表中的信息

 1  private void btnDelete_Click(object sender, EventArgs e)
 2    {
 3          if(treeView1.SelectedNode==null)
 4          {
 5                 MessageBox.Show("请选择要删除的节点!");
 6                 return;
 7            }
 8             //选中节点的id,也是其子节点的parentId
 9             int id = (int)treeView1.SelectedNode.Tag;
10             nodeDelete(id);//递归删除数据表中的数据
11             treeView1.SelectedNode.Remove();//删除控件中的节点
12 
13   }
14    //数据表中的数据的递归删除方法
15    public void nodeDelete(int id)
16  {
17             string sql = "select * from TreeTest where parentId="+id;
18             DataTable ds = sqlHelper.ExecuteDataTable(sql);
19             if (ds.Rows.Count > 0)
20             {
21                 //有子节点
22                 foreach(DataRow row in ds.Rows)
23                 {
24                     //先删除父节点
25                     string delete = "delete from TreeTest where id=" + id;
26                     int k = sqlHelper.ExecuteNonQuery(delete);
27                     //查找子节点,删除
28                     int id1 = (int)row["id"];
29                     nodeDelete(id1);
30                 }
31             }
32             else
33             { 
34                //没有子节点
35                 string delete = "delete from TreeTest where id="+id;
36                 int k = sqlHelper.ExecuteNonQuery(delete);
37             }
38 }
删除节点代码

4、TreeView控件的右键操作

TreeView控件的右键操作,需要两个winform窗体form3(图4-1),form4(图4-2),其中form3中放置treeview1控件,两个contextMenuStrip,contextMenuStrip1和contextMenuStrip2,

form4用于弹出菜单 填写要添加节点名称

 

图4-1

图4-2

contextMenuStrip1

contextMenuStrip2

4.1 Form4窗体的代码如下:

 1 public partial class Form4 : Form
 2  {
 3         public string nodeName
 4         {
 5             get { return textBox1.Text.Trim(); }
 6         }
 7         public Form4()
 8         {
 9             InitializeComponent();
10         }
11 
12         private void btnCancel_Click(object sender, EventArgs e)
13         {
14             DialogResult = DialogResult.Cancel;
15         }
16 
17         private void btnConfirm_Click(object sender, EventArgs e)
18         {
19             if(string.IsNullOrEmpty(textBox1.Text.Trim()))
20             {
21                 MessageBox.Show("请填写节点名称!");
22                 return;
23             }
24             DialogResult = DialogResult.OK;
25         }
26 }
form4窗体代码

4.2 form3窗体的代码如下:

 1 public partial class Form3 : Form
 2     {
 3         public Form3()
 4         {
 5             InitializeComponent();
 6         }
 7         private void treeView1_MouseDown(object sender, MouseEventArgs e)
 8         {
 9             if(e.Button==MouseButtons.Right)
10             {
11                 Point ClickPoint = new Point(e.X, e.Y);
12                 int x = e.X;
13                 int y = e.Y;
14                 TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
15                 if (CurrentNode is TreeNode)//判断你点的是不是一个节点
16                 {               
17                     treeView1.SelectedNode = CurrentNode;
18                     CurrentNode.ContextMenuStrip = this.contextMenuStrip1;                    
19                     contextMenuStrip1.Show(MousePosition);
20                 }
21                 else
22                 {
23                     treeView1.ContextMenuStrip = this.contextMenuStrip2;
24                     contextMenuStrip2.Show(MousePosition);
25                 }
26             }
27         }
28 
29         private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
30         {
31             Form4 f5 = new Form4();
32             if (f5.ShowDialog() == DialogResult.OK)
33             {
34               treeView1.SelectedNode.Nodes.Add(f5.nodeName);
35             }
36         }
37 
38         private void 删除选中节点ToolStripMenuItem_Click(object sender, EventArgs e)
39         {
40             treeView1.SelectedNode.Remove();
41         }
42 
43         private void 添加根节点ToolStripMenuItem1_Click(object sender, EventArgs e)
44         {
45             Form4 f4 = new Form4();
46             if (f4.ShowDialog() == DialogResult.OK)
47             {
48                 treeView1.Nodes.Add(f4.nodeName);
49             }
50         }
51 
52         private void 清空ToolStripMenuItem1_Click(object sender, EventArgs e)
53         {
54             treeView1.Nodes.Clear();
55         }
56     }
form3窗体代码

 4.3、示例中用到的sqlHelper.cs文件代码如下所示

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Data;
  6 using System.Data.SqlClient;
  7 using System.Windows.Forms;
  8 
  9 namespace CRMProject.DAL
 10 {
 11     class SqlHelper
 12     {
 13         static DataTable  dtInfo = new DataTable();    
 14         public static SqlConnection My_con;  //定义一个sqlConnection类型的公共变量My_con,用于判断数据库是否连接成功
 15 
 16 
 17         public static readonly string connstr = 
 18             ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
 19 
 20  public static int ExecuteNonQuery(string cmdText,
 21             params SqlParameter[] parameters)
 22         {
 23             using (SqlConnection conn = new SqlConnection(connstr))
 24             {
 25                 conn.Open();
 26                 using (SqlCommand cmd = conn.CreateCommand())
 27                 {
 28                     cmd.CommandText = cmdText;
 29                     cmd.CommandTimeout = 3000;
 30                     cmd.Parameters.AddRange(parameters);
 31                     return cmd.ExecuteNonQuery();
 32                 }
 33             }
 34         }
 35 
 36   public static void dgrd_Connection(string strSql, DataGridView dgrd, int start, int pagesize, string tableName)
 37         {
 38 
 39             try
 40             {
 41                 SqlDataAdapter adapter = new SqlDataAdapter(strSql, getcon());
 42                 DataSet dataSet = new DataSet();
 43                 adapter.Fill(dataSet, start, pagesize, tableName);
 44                 dtInfo = dataSet.Tables[tableName];
 45                 dgrd.DataSource = dataSet.Tables[tableName];
 46                 dgrd.AllowUserToAddRows = false;
 47 
 48             }
 49             catch { }
 50         }
 51 
 52         public static SqlConnection getcon()
 53         {
 54 
 55 
 56             My_con = new SqlConnection(connstr);   //用SqlConnection对象与指定的数据库相连接
 57             My_con.Open();  //打开数据库连接
 58             return My_con;  //返回SqlConnection对象的信息              
 59 
 60 
 61         }
 62         public static int Count(string strSql)
 63         {
 64             using (SqlConnection conn = new SqlConnection(connstr))
 65             {
 66                 conn.Open();
 67                 using (SqlCommand cmd = conn.CreateCommand())
 68                 {
 69                     try
 70                     {
 71                         cmd.CommandText = strSql;
 72                         cmd.CommandTimeout = 3000;
 73                         int n = int.Parse(cmd.ExecuteScalar().ToString());
 74                         return n;
 75 
 76                     }
 77                     catch { return 0; }
 78                 }
 79             }
 80         }
 81         public static object ExecuteScalar(string cmdText,
 82             params SqlParameter[] parameters)
 83         {
 84             using (SqlConnection conn = new SqlConnection(connstr))
 85             {
 86                 conn.Open();
 87                 using (SqlCommand cmd = conn.CreateCommand())
 88                 {
 89                     cmd.CommandText = cmdText;
 90                     cmd.CommandTimeout = 3000;
 91                     cmd.Parameters.AddRange(parameters);
 92                     return cmd.ExecuteScalar();
 93                 }
 94             }
 95         }
 96 
 97         public static DataTable ExecuteDataTable(string cmdText,
 98             params SqlParameter[] parameters)
 99         {
100             using (SqlConnection conn = new SqlConnection(connstr))
101             {
102                 conn.Open();
103                 using (SqlCommand cmd = conn.CreateCommand())
104                 {
105                     cmd.CommandText = cmdText;
106                     cmd.CommandTimeout = 3000;
107                     cmd.Parameters.AddRange(parameters);
108                     using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
109                     {
110                         DataTable dt = new DataTable();
111                         adapter.Fill(dt);
112                         return dt;
113                     }
114                 }
115             }
116         }
117 
118         public static SqlDataReader ExecuteDataReader(string cmdText,
119             params SqlParameter[] parameters)
120         {
121             SqlConnection conn = new SqlConnection(connstr);
122             conn.Open();
123             using (SqlCommand cmd = conn.CreateCommand())
124             {
125                 cmd.CommandText = cmdText;
126                 cmd.CommandTimeout = 3000;
127                 cmd.Parameters.AddRange(parameters);
128                 return cmd.ExecuteReader(CommandBehavior.CloseConnection);
129             }
130         }
131     }
132 }
sqlhelper.cs

 5、源码下载地址

链接:http://pan.baidu.com/s/1mi5DGi0 密码:t22u

 6、土豪打赏

          

posted @ 2016-05-27 15:07  学习靠自己  阅读(97030)  评论(7编辑  收藏