我们要使用treeView,首先需要对应树状图关系的表结构,如省市区的结构,大概如下
完成效果图(省市区结构),大概如下:
新增一个citys.aspx页面,在页面中添加treeView
<div> <asp:TreeView ID="compTreeView" runat="server" OnSelectedNodeChanged="compTreeView_SelectedNodeChanged"> </asp:TreeView> </div>
后台调用的方法
/// <summary> /// 递归添加树的节点 /// </summary> /// <param name="ParentID"></param> /// <param name="pNode"></param> public void AddTree(string ParentId, TreeNode pNode) { DataSet ds = (DataSet)this.ViewState["ds"]; DataView dvTree = new DataView(ds.Tables[0]); //过滤ParentID,得到当前的所有子节点 var code = ParentId == "" ? $"[code]=440000" : $"[parent_code]={ParentId}"; dvTree.RowFilter = code; foreach (DataRowView Row in dvTree) { TreeNode Node = new TreeNode(); if (pNode == null) { //添加根节点 Node.Text = Row["name"].ToString(); Node.Value = Row["code"].ToString(); compTreeView.Nodes.Add(Node); Node.Expanded = true; AddTree(Row["code"].ToString(), Node); //再次递归 } else { //̀添加当前节点的子节点 Node.Text = Row["name"].ToString(); Node.Value = Row["code"].ToString(); pNode.ChildNodes.Add(Node); Node.Expanded = false; AddTree(Row["code"].ToString(), Node); //再次递归 } } } /// <summary> /// 获取树状结构的数据 /// </summary> public void GetTreeData() { // 定义数据库连接 SqlConnection CN = new SqlConnection(); try { //初始化连接字符串 CN.ConnectionString = "data source=.;initial catalog=ACT_220820;user id=sa;Password=sa;"; CN.Open(); SqlDataAdapter adp = new SqlDataAdapter("select * from act_citys order by code asc", CN); DataSet ds = new DataSet(); adp.Fill(ds); this.ViewState["ds"] = ds; } catch (Exception) { //̀跳转程序的公共错误处理页面 } finally { CN.Close(); } //调用递归函数,完成树形结构的生成 AddTree("", (TreeNode)null); } /// <summary> /// compTreeView的选中节点事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void compTreeView_SelectedNodeChanged(object sender, EventArgs e) { //获取选中节点的value和text string nodeValue = compTreeView.SelectedNode.Value; string nodeText = compTreeView.SelectedNode.Text; //置选中节点的Selected属性为false compTreeView.SelectedNode.Selected = false; }
记得在后台的Page_load 添加
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { GetTreeData(); } }
其中compTreeView_SelectedNodeChanged()函数是节点选中事件,可以做这个方法做下业务。(如左边省市区树状结构,右边单位信息,通过点击对于节点过滤查询单位信息等)
标签:Node,code,WebForm,ds,compTreeView,简单,treeView,节点,Row From: https://www.cnblogs.com/xielong/p/16719494.html