TreeView右键菜单从数据库中读取,插入,删除,查找(高亮显示并展开),编辑(即地编辑)的例子 
这个项目包括二个文件,分别为From1.cs and FormCommon.cs,一个配置文件App.config 
Form1.cs

using  System;
using  System.Drawing;
using  System.Collections;
using  System.ComponentModel;
using  System.Windows.Forms;
using  System.Data;
using  System.Data.SqlClient;
using  System.Configuration;
namespace  Tree
{
///  
///  Form1 的摘要说明。
///  
public   class  Form1 : System.Windows.Forms.Form
{
private  System.Windows.Forms.TreeView treeView1;
private  System.Data.SqlClient.SqlConnection sqlConnection1;
///  
///  必需的设计器变量。
///  
private  System.ComponentModel.Container components  =   null ;
private  System.Windows.Forms.ContextMenu contextMenu1;
private  System.Windows.Forms.MenuItem menuAdd;
private  System.Windows.Forms.MenuItem menuDel;
private  System.Windows.Forms.MenuItem menuEdit;
private  System.Windows.Forms.MenuItem menuSearch;
private  ArrayList list;
private  ArrayList listnode;
private   string  strcomm;
private   bool  isselected = true ;
private  System.Windows.Forms.ListBox listBox1;
private  TreeNode selectnode ;
 
public  Form1()
{
//
//  Windows 窗体设计器支持所必需的
//
InitializeComponent();
 
//
//  TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
 
///  
///  清理所有正在使用的资源。
///  
protected   override   void  Dispose(  bool  disposing )
{
if ( disposing )
{
if  (components  !=   null ) 
{
components.Dispose();
}
}
base .Dispose( disposing );
}
 
#region  Windows 窗体设计器生成的代码
///  
///  设计器支持所需的方法 - 不要使用代码编辑器修改
///  此方法的内容。
///  
private   void  InitializeComponent()
{
this .treeView1  =   new  System.Windows.Forms.TreeView();
this .contextMenu1  =   new  System.Windows.Forms.ContextMenu();
this .menuAdd  =   new  System.Windows.Forms.MenuItem();
this .menuDel  =   new  System.Windows.Forms.MenuItem();
this .menuEdit  =   new  System.Windows.Forms.MenuItem();
this .menuSearch  =   new  System.Windows.Forms.MenuItem();
this .sqlConnection1  =   new  System.Data.SqlClient.SqlConnection();
this .listBox1  =   new  System.Windows.Forms.ListBox();
this .SuspendLayout();
//  
//  treeView1
//  
this .treeView1.AllowDrop  =   true ;
this .treeView1.ContextMenu  =   this .contextMenu1;
this .treeView1.HotTracking  =   true ;
this .treeView1.ImageIndex  =   - 1 ;
this .treeView1.LabelEdit  =   true ;
this .treeView1.Location  =   new  System.Drawing.Point( 16 ,  16 );
this .treeView1.Name  =   " treeView1 " ;
this .treeView1.SelectedImageIndex  =   - 1 ;
this .treeView1.Size  =   new  System.Drawing.Size( 200 ,  388 );
this .treeView1.TabIndex  =   0 ;
this .treeView1.MouseDown  +=   new  System.Windows.Forms.MouseEventHandler( this .treeView1_MouseDown);
this .treeView1.AfterSelect  +=   new  System.Windows.Forms.TreeViewEventHandler( this .treeView1_AfterSelect);
this .treeView1.AfterLabelEdit  +=   new  System.Windows.Forms.NodeLabelEditEventHandler( this .treeView1_AfterLabelEdit);
//  
//  contextMenu1
//  
this .contextMenu1.MenuItems.AddRange( new  System.Windows.Forms.MenuItem[] {
  this .menuAdd,
  this .menuDel,
  this .menuEdit,
  this .menuSearch});
//  
//  menuAdd
//  
this .menuAdd.Index  =   0 ;
this .menuAdd.Text  =   " 新增 " ;
this .menuAdd.Click  +=   new  System.EventHandler( this .menuAdd_Click);
//  
//  menuDel
//  
this .menuDel.Index  =   1 ;
this .menuDel.Text  =   " 删除 " ;
this .menuDel.Click  +=   new  System.EventHandler( this .menuDel_Click);
//  
//  menuEdit
//  
this .menuEdit.Index  =   2 ;
this .menuEdit.Text  =   " 编辑 " ;
this .menuEdit.Click  +=   new  System.EventHandler( this .menuEdit_Click);
//  
//  menuSearch
//  
this .menuSearch.Index  =   3 ;
this .menuSearch.Text  =   " 查找 " ;
this .menuSearch.Click  +=   new  System.EventHandler( this .menuSearch_Click);
//  
//  listBox1
//  
this .listBox1.ItemHeight  =   12 ;
this .listBox1.Location  =   new  System.Drawing.Point( 244 ,  20 );
this .listBox1.Name  =   " listBox1 " ;
this .listBox1.Size  =   new  System.Drawing.Size( 288 ,  376 );
this .listBox1.TabIndex  =   1 ;
//  
//  Form1
//  
this .AutoScaleBaseSize  =   new  System.Drawing.Size( 6 ,  14 );
this .ClientSize  =   new  System.Drawing.Size( 564 ,  422 );
this .Controls.Add( this .listBox1);
this .Controls.Add( this .treeView1);
this .Name  =   " Form1 " ;
this .Text  =   " Form1 " ;
this .Load  +=   new  System.EventHandler( this .Form1_Load);
this .ResumeLayout( false );
 
}
#endregion
 
///  
///  应用程序的主入口点。
///  
[STAThread]
static   void  Main() 
{
Application.Run( new  Form1());
}
 
private  DataSet ds;
private  SqlDataAdapter sqlDataAdapter1;
private   int  maxnodeid;
 
private   void  Form1_Load( object  sender, System.EventArgs e)
{
string  strconn = ConfigurationSettings.AppSettings[ " ConnStr " ];
sqlConnection1  =   new  SqlConnection(strconn);
this .sqlConnection1.Open();
// 填充DataSet
this .CreateDataSet();
// 从数据库中读取数据,通过递归生成树。
InitTree( this .treeView1.Nodes, " 0 " );
 
}

private   void  CreateDataSet()
{
this .sqlDataAdapter1 = new  SqlDataAdapter( " select * from s_menu  " , this .sqlConnection1);
this .ds = new  DataSet();
this .sqlDataAdapter1.Fill(ds, " tree " ); 
}
private   void  InitTree(TreeNodeCollection Nds, string  parentId)
{
DataView dv = new  DataView();
TreeNode tmpNd;
string  intId;
dv.Table = ds.Tables[ " tree " ];
dv.RowFilter = " ParentId=' "   +  parentId  +   " ' "  ;
foreach (DataRowView drv  in  dv)
{
tmpNd = new  TreeNode();
tmpNd.Tag = drv[ " NodeId " ].ToString();
tmpNd.Text = drv[ " NodeName " ].ToString();
Nds.Add(tmpNd);
intId = drv[ " ParentId " ].ToString();
InitTree(tmpNd.Nodes,tmpNd.Tag.ToString());
}

// 新增节点操作
private   void  insert( string  type)
{ // 判断是新增树节点,还是子节点.
string  strinsert = " insert into s_menu values('{0}','{1}','{2}') " ; 
string  strformat = "" ;
if (type == " sub " )
strformat = string .Format(strinsert,maxnodeid.ToString(), this .selectnode.Tag.ToString(), this .strcomm);
else
strformat = string .Format(strinsert,maxnodeid.ToString(), " 0 " , this .strcomm); 
SqlCommand cmd = new  SqlCommand(strformat, this .sqlConnection1); 
cmd.ExecuteNonQuery(); 
}
// 为新增节点算出最大的节点值,并以此值作为新增的节点ID值
private   int  GetMaxNodeid()
{
int  pre = 0 ,last = 0 ;
DataSet maxds = new  DataSet();
this .sqlDataAdapter1 = new  SqlDataAdapter( " select nodeid from s_menu order by nodeid " , this .sqlConnection1);
this .sqlDataAdapter1.Fill(maxds);
for ( int  i = 0 ;i{
if (i + 1 {
pre = int .Parse(maxds.Tables[ 0 ].Rows[i][ 0 ].ToString());
last = int .Parse(maxds.Tables[ 0 ].Rows[i + 1 ][ 0 ].ToString()); 
if (last - pre != 1 )
return  pre + 1 ;
}
}
return  last + 1 ; 

private   void  getallnode(TreeNode tn)
{
foreach (TreeNode node  in  tn.Nodes)
{
list.Add(node.Tag.ToString());
if (node.Nodes.Count > 0 )
{
getallnode(node);
}
}
}
 
private   void  treeView1_MouseDown( object  sender, System.Windows.Forms.MouseEventArgs e)
{
// 判断是否点击了某个节点
this .selectnode =   this .treeView1.GetNodeAt (e.X ,e.Y );
if (selectnode == null )
this .isselected = false ;
else
this .isselected = true ;

private   void  menuAdd_Click( object  sender, System.EventArgs e)
{ // 判断是否点击了某个节点,若没有点击了,则是新增一个树节点
if (isselected == false )
{ // 算出新增树节点的ID值
maxnodeid = GetMaxNodeid();
TreeNode tmpNd = new  TreeNode();
// 赋值
tmpNd.Tag = this .maxnodeid.ToString();
FormCommon frmCommon = new  FormCommon();
DialogResult result =  frmCommon.ShowDialog();
if (result == DialogResult.OK)
{ // 取到新增树节点的文本值
tmpNd.Text = frmCommon.strcomm;
this .strcomm = frmCommon.strcomm;
// 新增树节点
this .treeView1.Nodes.Add(tmpNd);
// 插入数据库(说明插入的是树节点)
this .insert( " root " );
// 展开
this .selectnode.Expand();
}
}
else
{ // 判断是否点击了某个节点,若点击了,则是新增一个子节点
this .contextAddSub();


private   void  contextAddSub()
{ // 得到新增子节点的ID值
maxnodeid = GetMaxNodeid();
TreeNode tmpNd = new  TreeNode();
// 赋值
tmpNd.Tag = this .maxnodeid.ToString(); 
FormCommon frmCommon = new  FormCommon();
DialogResult result =  frmCommon.ShowDialog();
if (result == DialogResult.OK)
{ // 取到新增树节点的文本值
tmpNd.Text = frmCommon.strcomm;
this .strcomm = frmCommon.strcomm;
// 新增子节点
this .selectnode.Nodes.Add(tmpNd);
// 插入数据库(说明插入的是子节点)
this .insert( " sub " );
// 展开
this .treeView1.SelectedNode.Expand(); 

}
// 删除节点操作
private   void  menuDel_Click( object  sender, System.EventArgs e)
{ // 新建一个ArrayList,用于保存要删除的节点下边的所有子节点
list = new  ArrayList();
if ( this .isselected == true )
{ // 得到删除的节点下边的所有子节点
getallnode( this .selectnode);
// 把要删除的节点也加进去
list.Add( this .selectnode.Tag.ToString());
// 循环从数据库中删除
for ( int  i = 0 ;i{
string  strdel = " delete s_menu where nodeid='{0}' " ; 
string  strformat = "" ; 
strformat = string .Format(strdel,list[i]); 
SqlCommand cmd = new  SqlCommand(strformat, this .sqlConnection1); 
cmd.ExecuteNonQuery();
}
// 从树中删除
this .selectnode.Remove();

}
// 修改节点的值
private   void  menuEdit_Click( object  sender, System.EventArgs e)
{
if ( this .isselected == true )
{
FormCommon frmCommon = new  FormCommon();
DialogResult result =  frmCommon.ShowDialog();
if (result == DialogResult.OK)
{
string  strdel = " update s_menu set nodename= '{1}' where nodeid='{0}' " ; 
string  strformat = "" ; 
strformat = string .Format(strdel, this .selectnode.Tag.ToString(),frmCommon.strcomm); 
SqlCommand cmd = new  SqlCommand(strformat, this .sqlConnection1); 
cmd.ExecuteNonQuery();
this .selectnode.Text = frmCommon.strcomm; 
}

}
// 遍历所有节点.查找值
private   void  getvaluenode(TreeNodeCollection tn, string  value)
{
foreach (TreeNode node  in  tn)

if (node.Nodes.Count > 0 )
{
getvaluenode(node.Nodes,value);
}
if (node.Text == value)
 listnode.Add(node);
}

private   void  menuSearch_Click( object  sender, System.EventArgs e)
{
int  j,k;
this .listnode = new  ArrayList();
FormCommon frmCommon = new  FormCommon();
DialogResult result =  frmCommon.ShowDialog();
if (result == DialogResult.OK)
{
TreeNode n  = new  TreeNode();
TreeNode temp = new  TreeNode();
// 下面的函数是填充listnode;
getvaluenode( this .treeView1.Nodes,frmCommon.strcomm);
for ( int  i = 0 ;i{
j = 0 ;k = 0 ;
n = (TreeNode)listnode[i];
if  (n  !=   null )
{
temp = n;
// 得到上面结点的数量,并将数量保存到变量j;
for (;n.Parent != null ;)
{
n = n.Parent;
j ++ ;
}
// 恢复原值 
n = temp;
// 新建一个树结点数组做保存得到查询到的所有节点.
TreeNode[] m = new  TreeNode[j];
for (;n.Parent != null ;)
{
n = n.Parent;
m[k] = n;
k ++ ; 
}
for ( int  p = 0 ;pm[p].Expand();
n = temp;
n.ForeColor = Color.Red;
}
}

}
private   void  treeView1_AfterLabelEdit( object  sender, System.Windows.Forms.NodeLabelEditEventArgs e)
{
if ( this .treeView1.SelectedNode.Text != null )
{
string  strdel = " update s_menu set nodename= '{1}' where nodeid='{0}' " ;
  string  strformat = "" ;strformat = string .Format(strdel, this .treeView1.SelectedNode.Tag.ToString(),e.Label.ToString());SqlCommand cmd = new  SqlCommand(strformat, this .sqlConnection1); 
cmd.ExecuteNonQuery();
 
}

private   void  treeView1_AfterSelect( object  sender, System.Windows.Forms.TreeViewEventArgs e)
{
this .listBox1.Items.Clear();
this .listBox1.Items.Add( this .treeView1.SelectedNode.FullPath.ToString());
}
}
}

//formCommon.cs

using  System;
using  System.Drawing;
using  System.Collections;
using  System.ComponentModel;
using  System.Windows.Forms; 
namespace  Tree
{
///  
///  FormCommon 的摘要说明。
///  
public   class  FormCommon : System.Windows.Forms.Form
{
private  System.Windows.Forms.TextBox txtCommon;
private  System.Windows.Forms.Button btnOK;
///  
///  必需的设计器变量。
///  
private  System.ComponentModel.Container components  =   null ;
public   string  strcomm;
public  FormCommon()
{
//
//  Windows 窗体设计器支持所必需的
//
InitializeComponent();
 
//
//  TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//

///  
///  清理所有正在使用的资源。
///  
protected   override   void  Dispose(  bool  disposing )
{
if ( disposing )
{
if (components  !=   null )
{
components.Dispose();
}
}
base .Dispose( disposing );

#region  Windows 窗体设计器生成的代码
///  
///  设计器支持所需的方法 - 不要使用代码编辑器修改
///  此方法的内容。
///  
private   void  InitializeComponent()
{
this .txtCommon  =   new  System.Windows.Forms.TextBox();
this .btnOK  =   new  System.Windows.Forms.Button();
this .SuspendLayout();
//  
//  txtCommon
//  
this .txtCommon.Location  =   new  System.Drawing.Point( 36 ,  16 );
this .txtCommon.Name  =   " txtCommon " ;
this .txtCommon.TabIndex  =   0 ;
this .txtCommon.Text  =   "" ;
//  
//  btnOK
//  
this .btnOK.DialogResult  =  System.Windows.Forms.DialogResult.OK;
this .btnOK.Location  =   new  System.Drawing.Point( 48 ,  52 );
this .btnOK.Name  =   " btnOK " ;
this .btnOK.TabIndex  =   1 ;
this .btnOK.Text  =   " 确定 " ;
this .btnOK.Click  +=   new  System.EventHandler( this .btnOK_Click);
//  
//  FormCommon
//  
this .AutoScaleBaseSize  =   new  System.Drawing.Size( 6 ,  14 );
this .ClientSize  =   new  System.Drawing.Size( 176 ,  98 );
this .Controls.Add( this .btnOK);
this .Controls.Add( this .txtCommon);
this .Name  =   " FormCommon " ;
this .Text  =   " FormCommon " ;
this .ResumeLayout( false );
 
}
#endregion
 
private   void  btnOK_Click( object  sender, System.EventArgs e)
{
if ( this .txtCommon.Text == "" )
{
MessageBox.Show( " 不能为空 " );
this .DialogResult = DialogResult.None;
}
else
this .strcomm = this .txtCommon.Text; 
}
}
}

//配置文件App.Config

// 数据库脚本 
if  exists (select  *  from dbo.sysobjects where id  =  object_id(N ' [dbo].[S_Menu] ' ) and OBJECTPROPERTY(id, N ' IsUserTable ' )  =   1 )
drop table [dbo].[S_Menu]
GO
 
CREATE TABLE [dbo].[S_Menu] (
[NodeId] [ char ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ParentId] [ char ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL ,
[NodeName] [nvarchar] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]
GO______________________________ 

Nodeid parentid nodename 
10000 0 湖北省 
10001 10000 武汉市
10002 10000 宜昌市
10003 0 广东省

转载于:https://www.cnblogs.com/CampagniaTe/archive/2007/07/31/837309.html

C#winform TreeView编程相关推荐

  1. C# WinForm TreeView用法总结

    TreeView用法值得总结一下,今天用到了,一时忘了怎样执行选中节点事件. private void BindTreeView() {     treeView1.LabelEdit = false ...

  2. 浅述WinForm多线程编程与Control.Invoke的应用

    在WinForm开发中,我们通常不希望当窗体上点了某个按钮执行某个业务的时候,窗体就被卡死了,直到该业务执行完毕后才缓过来.一个最直接的方法便是使用多线程.多线程编程的方式在WinForm开发中必不可 ...

  3. C# winform TreeView 屏蔽双击展开/折叠子节点

    一搜索这个基本都是一样的通过事件来处理 思路: 1.通过点击事件,记录点击的节点信息(是否为双击了节点的bounds,是的话在第二步cancel掉) 2.通过BeforeExpand.BeforeCo ...

  4. C# winform treeview GDI+流程连线 流程图 树形流程图

    C# winform treeview GDI+流程连线 流程图 树形流程图 TreeView_Paint的方法呈现效果,具体如下 1.点击连线按钮开始准备连线 2.点击第一个连线的起始节点 3.再点 ...

  5. C# WinForm TreeView

    C#WinForm中TreeView默认展开设置 1.默认全部展开,在Form1_Load事件中添加: treeView1.ExpandAll(); 2.默认展开第一个节点,或默认节点,在Form1_ ...

  6. c# WINFORM SOCKET编程-简单聊天程序(服务端)

    初学C#的SOCKET编程,照着网上的代码写下来,程序总是有问题,经过自己长时间的调试,完成程序,以下是原码,有需要可以参考一下,还不完善,欢迎大家批评指正.(这里的代码没更新,附件重新上传更新,在另 ...

  7. c# winform TreeView与ListView的项互相拖动的应用[转载]

    转载modede 很久没写教程了,停顿了有两年之久了.今天我们来讨论讨论 winform 中TreeView与ListView,通观两者很相似,只是一个是树形结构,一个是列表结构. 今天自己创建的群里 ...

  8. C# winform treeview node添加右键菜单并选中节点

    2019独角兽企业重金招聘Python工程师标准>>> 转自http://www.cnblogs.com/luluping/archive/2010/03/03/1677206.ht ...

  9. C# winform treeview节点重命名

    方法一: 1 int nodeIndex = 0; 2 bool nodeChanged = false; 3 4 //右键点击,就进入修改状态 5 private void treeView1_No ...

最新文章

  1. 【转】完美解决Asp.Net的MasterPage中添加JavaScript路径问题
  2. 10行代码AC——UVA 11538-Chess Queen(数学规律+数列,附详细讲解)
  3. Android串口编程--开关灯Demo(附源码)
  4. 【热修复】Andfix源码分析
  5. Python调用API接口的几种方式
  6. 4006.Cacti集监控IBM刀片服务器温度和风扇运行状态
  7. [含论文+源码等]javaweb银行柜员业务绩效考核系统
  8. 平方和误差函数--代价函数(机器学习)
  9. ​以数据科学家的眼光投资,你可能会一夜暴富
  10. pubwin操作记录
  11. 微带线 带状线 过孔的时延对比
  12. 思必驰完成5亿元融资,国家禁毒大数据在昆明投入使用
  13. php订单表设计,订单详情表,与,订单表 怎么做?
  14. OBS直播软件-简介
  15. hbuilder 断点_Hbuilder配置php断点调试
  16. 中国公认的大学生计算机编程第一人:楼天城
  17. 【多线程】优雅使用线程池结合CompletableFuture实现异步编排
  18. 互联网早报:淘宝发布购物车分享功能,双十一有望分享微信朋友圈
  19. java微信支付v3系列——7.微信支付之申请退款
  20. gcc编译 -I头文件目录 -L lib库目录 -l动态库文件

热门文章

  1. 简单的理解position与anchorPoint
  2. spring及boot注解
  3. utf8mb4_unicode_ci、utf8mb4_general_ci的区别总结
  4. Android Q 适配,看这篇就妥了
  5. 51单片机实验之流水灯和交替闪烁
  6. OCT-模拟集成电路设计的九个境界
  7. 超详细——入门Github的代码上传
  8. 编译报错:needed by ‘out/target/product/XXX.apk.....
  9. 学海灯塔新增学习笔记上传功能
  10. 正则化,岭回归Shrinkage,lasso稀疏性推导和论文总结