只有点击Node的是才进行绑定:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string connstr = ConfigurationManager.AppSettings["ConnString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TreeBind();
}
}
protected void TreeBind()
{
SqlConnection conn = new SqlConnection(connstr);
string sql = "select distinct(bsf),bt from dbo.ZYJHYSJ where fjh='00000000000'";
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
TreeNode node = new TreeNode(dr["bt"].ToString(), dr["bsf"].ToString());
CreateChildTree(node, dr["bsf"].ToString()); //得到子节点
TreeView1.Nodes.Add(node);
}
}
public void CreateChildTree(TreeNode parentNode, string parentID)
{
SqlConnection conn = new SqlConnection(connstr);
string sql = "select distinct(bsf),bt from dbo.ZYJHYSJ where fjh=@rootID";
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.Add("@rootID", SqlDbType.NVarChar).Value = parentID;
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
TreeNode node = new TreeNode(dr["bt"].ToString(), dr["bsf"].ToString());
parentNode.ChildNodes.Add(node);
}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
//TreeNode parentNode = TreeView1.SelectedNode;
//string parentID = TreeView1.SelectedValue.ToString();
//if (parentNode.Depth <= 2)
//{
// parentNode.ChildNodes.Clear();
// CreateChildTree(parentNode, parentID);
//}
}
protected void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
if (e.Node.Depth <= 1)
{
foreach (TreeNode Tn in e.Node.ChildNodes)
{
CreateChildTree(Tn, Tn.Value);
}
}
}
protected void TreeView1_TreeNodeCollapsed(object sender, TreeNodeEventArgs e)
{
if (e.Node.Depth <= 1)
{
foreach (TreeNode Tn in e.Node.ChildNodes)
{
Tn.ChildNodes.Clear();
Tn.Collapse();
}
}
}