.aspx代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="中国市区县.aspx.cs" Inherits="中国市区县" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="tv_china" runat="server" ExpandDepth="0"> 注释:ExpandDepth="0" 表示刚开始结点全部闭合
</asp:TreeView>
</div>
</form>
</body>
</html>
.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.OleDb;
public partial class 中国市区县 : System.Web.UI.Page
{
string str_cnn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=";
string str_sourcefile = "~/data/china.mdb";
OleDbConnection cnn;
OleDbCommand cmd;
OleDbDataReader datar;
string str_sql;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
makeTree();
}
}
protected void makeTree() {
TreeNode _tnode, _parentNode;
string str_conn = str_cnn + MapPath(str_sourcefile);
cnn = new OleDbConnection(str_conn);
cnn.Open();
//构建一级(省)
str_sql = "select p_id,p_name from t_province";
cmd = new OleDbCommand(str_sql, cnn);
datar = cmd.ExecuteReader();
while (datar.Read())
{
_tnode = new TreeNode();
_tnode.Text = datar["p_name"].ToString();
_tnode.Value="p_"+datar["p_id"].ToString();
tv_china.Nodes.Add(_tnode);
}
//构建二级(市)
str_sql = "select c_id,c_name,c_pid from t_city";
cmd = new OleDbCommand(str_sql, cnn);
datar = cmd.ExecuteReader();
while (datar.Read())
{
_parentNode = tv_china.FindNode("p_" + datar["c_pid"].ToString());//找到父节点
_tnode = new TreeNode();
_tnode.Text = datar["c_name"].ToString();
_tnode.Value = "c_" + datar["c_id"].ToString();
_parentNode.ChildNodes.Add(_tnode);//添加到父节点中,用到了.ChildNode的方法
}
//构建三级(区)
str_sql = "SELECT T_City.c_pid, T_City.c_id, T_District.d_id, T_District.d_name FROM T_District INNER JOIN T_City ON T_District.d_cid = T_City.c_id";
cmd = new OleDbCommand(str_sql, cnn);
datar = cmd.ExecuteReader();
while (datar.Read())
{
_parentNode = tv_china.FindNode("p_" + datar["c_pid"].ToString() + "/c_" + datar["c_id"].ToString());
_tnode = new TreeNode();
_tnode.Text = datar["d_name"].ToString();
_tnode.Value = "d_" + datar["d_id"].ToString();
_parentNode.ChildNodes.Add(_tnode);
}
cnn.Close();
}
}
效果如下:
考虑到此方法占用系统资源较为严重,下节介绍局部刷新的方法。
标签:tnode,构建,str,cnn,ToString,省市区,TreeView,id,datar From: https://blog.51cto.com/u_15866446/5844715