treeView
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataTable dt; private void Form1_Load(object sender, EventArgs e) { using(SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=sa;database=master")) { conn.Open(); SqlDataAdapter sqlda = new SqlDataAdapter("select * from CS_Info", conn); DataSet ds = new DataSet(); sqlda.Fill(ds); dt= ds.Tables[0]; } RootTree(); } /// <summary> /// 添加根节点 /// </summary> public void RootTree() { try { DataRow[] dr = dt.Select("pid=0");//找到所有的根节点信息 DataTable dt_RootTree = dt.Clone(); foreach(DataRow a in dr ) { dt_RootTree.ImportRow(a); } foreach (DataRow row in dt_RootTree.Rows)//添加根节点 { TreeNode nox = new TreeNode(); nox.Text = row["name"].ToString(); nox.Tag = Convert.ToInt32(row["id"].ToString()); nox.ExpandAll(); this.treeView1.Nodes.Add(nox);//往控件中添加根节点 ChildTree(nox);//添加子节点 } } catch { } } /// <summary> /// 添加子节点 /// </summary> /// <param name="nod">父节点</param> public void ChildTree(TreeNode nod) { try { DataRow[] dr = dt.Select("Pid="+nod.Tag);//根据传来的父节点的id【在添加父节点的方法中 把 id值 赋给了Tag】筛选,判断该根节点是否有字节点的存在 DataTable dt_ChildTree = dt.Clone(); foreach (DataRow a in dr) { dt_ChildTree.ImportRow(a);//将该跟节点下的子节点信息 赋给dt_ChildTree } foreach (DataRow row in dt_ChildTree.Rows)//遍历dt_ChildTree 在该根节点上添加子节点 { TreeNode temp = new TreeNode(); temp.Text = row["name"].ToString(); temp.Tag = row["id"].ToString(); temp.ExpandAll(); nod.Nodes.Add(temp); } } catch { } } bool bl = true;// //显示选中的节点信息 tag 和text值
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (!bl)
{
MessageBox.Show("Tag:" + e.Node.Tag.ToString() + " ; Text:" + e.Node.Text.ToString());
}
else
{
bl = false;
}
}
}
}
create table CS_Info
(
id int,
name nvarchar(50),
Pid int
)
insert into CS_Info values(1,'数学',0) insert into CS_Info values(2,'语文',0) insert into CS_Info values(3,'英语',0) insert into CS_Info values(4,'美术',0) insert into CS_Info values(5,'音乐',0) insert into CS_Info values(6,'函数',1) insert into CS_Info values(7,'离散数学',1) insert into CS_Info values(8,'概率论',1) insert into CS_Info values(9,'线性代数',1) insert into CS_Info values(10,'微积分',1) insert into CS_Info values(11,'诗',2) insert into CS_Info values(12,'词',2) insert into CS_Info values(13,'歌',2) insert into CS_Info values(14,'赋',2) insert into CS_Info values(15,'论语',2) insert into CS_Info values(16,'四级',3) insert into CS_Info values(17,'托福',3) insert into CS_Info values(18,'国画',4) insert into CS_Info values(19,'水彩',4) insert into CS_Info values(20,'美声',5) insert into CS_Info values(21,'流行音乐',5) insert into CS_Info values(22,'神学',0)