这里采用了在页面一loading就把数据绑到TreeView的各节点的方式,而不是在展开时再作子节点的绑定,因此在点击父节点时就不会有刷新的感觉了。呵呵,代码并没优化.......
aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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">
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
</form>
</body>
</html>
.cs文件:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTree();
}
}
public void BindTree()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CreativeConnectionString"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter("select * from Province", con);
DataSet ds = new DataSet();
sda.Fill(ds, "Province");
TreeNode parentnode;
TreeNode childnode;
TreeNode townnode;
//TreeView1.ShowLines = true;
foreach (DataRow parentrow in ds.Tables["Province"].Rows)
{
//绑定第一层节点
parentnode = new TreeNode(parentrow["ProvinceName"].ToString(), parentrow["ProvinceId"].ToString(), "Images/shareddocuments.gif");
//运行时候先不展开子节点
parentnode.Expanded = false;
TreeView1.Nodes.Add(parentnode);
SqlDataAdapter adapter = new SqlDataAdapter("select * from City where ProvinceId =" + parentrow["ProvinceId"].ToString(), con);
adapter.Fill(ds, "City");
if (ds.Tables["City"].Rows.Count > 0)
{
//绑定第二层节点
foreach (DataRow childrow in ds.Tables["City"].Rows)
{
childnode = new TreeNode(childrow["CityName"].ToString(), childrow["CityId"].ToString(), "Images/dot.gif");
parentnode.ChildNodes.Add(childnode);
SqlDataAdapter adapter2 = new SqlDataAdapter("select townname from town where cityid=" + childrow["CityId"].ToString(),con);
adapter2.Fill(ds, "Town");
childnode.Expanded = false;
if (ds.Tables["Town"].Rows.Count > 0)
{
//绑定第三层节点
foreach (DataRow townrow in ds.Tables["Town"].Rows)
{
townnode = new TreeNode(townrow["townname"].ToString(), townrow["townname"].ToString(), "Images/log.gif");
childnode.ChildNodes.Add(townnode);
} ds.Tables["Town"].Clear();
}
}
ds.Tables["City"].Clear();
}
}
con.Close();
}
}
建立如下关系
1,Province
ProvinceID int 主键 自增
ProvinceName varchar(50)
2,City
CityID int 主键 自增
ProvinceID int 外键
CityName varchar(50)
3,Town
Townid int 主键 自增
Townname varchar(50)
Cityid int 外键