treeView 控件的用法实例 以及 datatable的基本用法
<div id="cnblogs_post_body"><div class="cnblogs_Highlighter">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; } 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;
}
}
}
}
页:
[1]