public partial class WebForm1 : System.Web.UI.Page { DataSet dsTreeView = new DataSet(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GetTreeView(); InitTree("", null); TreeView1.ExpandDepth = 0;//展开目录 TreeView1.Nodes[0].Expanded = true;//默认只展开第2层目录 } } private void InitTree(string parent_code, TreeNode parent_node) { DataView dv = dsTreeView.Tables[0].DefaultView; dv.RowFilter = "[parent_code] = '" + parent_code + "'"; foreach (DataRowView Row in dv) { TreeNode node = new TreeNode(); node.SelectAction = TreeNodeSelectAction.Expand; if (parent_node == null)//根节点 { node.Text = Row["area_name"].ToString(); node.Value = Row["area_code"].ToString(); this.TreeView1.Nodes.Add(node); InitTree(Row["area_code"].ToString(), node);//递归 } else { node.Text = "<div onclick="javascript:SetView('" + Row["area_name"].ToString() + "')">" + Row["area_name"].ToString() + "</div>";//绑定前台JS事件 node.Value = Row["area_code"].ToString(); parent_node.ChildNodes.Add(node); InitTree(Row["area_code"].ToString(), node);//递归 } } } /// <summary> /// 数据源 /// </summary> private void GetTreeView() { SqlConnection sqlConn = new SqlConnection("server=.;database=test;uid=test;pwd=test"); SqlDataAdapter adp = new SqlDataAdapter("select area_code,area_name,parent_code from tbl_all_AreaList where area_code<>parent_code", sqlConn); adp.Fill(dsTreeView); } }