作者:麦尔小哈PICA | 来源:互联网 | 2023-09-01 16:45
结合数据库获得父节点和子节点信息数值:
.aspx代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TreeView控件.aspx.cs" Inherits="TreeView控件" %>
<%=DateTime.Now.ToLongTimeString() %>
Onselectednodechanged="TreeView1_SelectedNodeChanged">
<%--为了不使整个页面刷新,引入ajax局部刷新,提高显示速度。以下是标准程序:
此处填入内容
--%>
<%=DateTime.Now.ToLongTimeString() %>
TEXT:
VALUE:
VALUEPATH:
.aspx.cs代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class TreeView控件 : System.Web.UI.Page
{
string con = "server=localhost\\SQL2005 ;uid=sa;pwd=1111qq;database=DBPromary";
SqlConnection conn;
SqlCommand cmd;
SqlDataReader datar;
string str_sql;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
maketree();
}
}
protected void maketree() {
//省
TreeNode _tNode,_ParentNode;
cOnn= new SqlConnection(con);
conn.Open();
str_sql="select * from promary";
cmd = new SqlCommand(str_sql, conn);
datar = cmd.ExecuteReader();
while (datar.Read()){
_tNode=new TreeNode();//实例化结点
_tNode.Text=datar["proName"].ToString();
_tNode.Value="p_"+datar["proID"].ToString();
TreeView1.Nodes.Add(_tNode);//结点加到TreeView上
}
conn.Close();
//city
cOnn= new SqlConnection(con);
conn.Open();
str_sql = "select * from city";
cmd = new SqlCommand(str_sql, conn);
datar = cmd.ExecuteReader();
while (datar.Read())
{
_ParentNode = TreeView1.FindNode("p_"+datar["proID"].ToString());//寻找父节点
_tNode=new TreeNode();//实例化子节点
_tNode.Text=datar["cityName"].ToString();//子节点的显示
_tNode.Value="c_"+datar["cityID"].ToString();//子节点的数值
_ParentNode.ChildNodes.Add(_tNode);//将子节点加到找到的父节点上
}
conn.Close();
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
TreeNode _tnode = TreeView1.SelectedNode;//SelectedNode方法找到选中的结点
lbl_TEXT.Text = _tnode.Text;
lbl_VALUE.Text = _tnode.Value;
lbl_VALUEPATH.Text = _tnode.ValuePath;
}
}
效果如下图:
引入Ajax之后只会刷新部分页面,通过时间条的刷新可以看出。这样会提高页面刷新效率。