首页 > 代码库 > 动态构建TreeView(中国省市区)

动态构建TreeView(中国省市区)

.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=http://www.mamicode.com/"p_"+datar["p_id"].ToString();>
效果如下:


考虑到此方法占用系统资源较为严重,下节介绍局部刷新的方法。

动态构建TreeView(中国省市区)