定义建立子节点函数(递归):
class Class1
{
public void GetChildTree(string pid, TreeNode tns)
{
SqlConnection con = new SqlConnection("Persist Security Info=False;User id=sa;pwd=123;database=WDERPDATA_001;server=(local)");
con.Open();
string sql = "select * from TBASE_DEPT ORDER BY BM_DEPT_CODE";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
//提交查询 获取结果数据集
DataSet ds = new DataSet();
sda.Fill(ds, "TBASE_DEPT");
//获取TBASE_DEPT表
DataTable dt = ds.Tables["TBASE_DEPT"];
// string two = "len(BM_DEPT_CODE)=4 and SUBSTRING(BM_DEPT_CODE,1,2)=" + tdr1["BM_DEPT_CODE"];
string one;
if ( tns.Tag.ToString().CompareTo("0")==0 )
{
one = "len(BM_DEPT_CODE)=" + pid + "+2 "; //and SUBSTRING(BM_DEPT_CODE,1," + pid + ")=" +tns.Tag;
}else
one = "len(BM_DEPT_CODE)=" + pid + "+2 and SUBSTRING(BM_DEPT_CODE,1," + pid + ")=" +tns.Tag;
DataRow[] rows = dt.Select(one);
foreach(DataRow tdr1 in rows)
{
TreeNode tn1 = new TreeNode();
tn1.Tag = tdr1["BM_DEPT_CODE"];
tn1.Text = tdr1["BM_DEPT_NAME"].ToString();
tns.Nodes.Add(tn1);
string pid1 = tdr1["BM_DEPT_CODE"].ToString().Length.ToString();
// MessageBox.Show(pid1);
GetChildTree(pid1, tn1);
}
调用部分:
TreeNode node1 = new TreeNode();
node1.Tag = "0";
node1.Text = "珠海供电公司";
this.treeView1.Nodes.Add(node1);
Class1 cl1 = new Class1();
cl1.GetChildTree("0", node1);
附录:
http://www.pudn.com/downloads110/sourcecode/database/detail454408.html
http://blog.youkuaiyun.com/ybb575/archive/2007/10/11/1819479.aspx