这几天上班没事做,也不好打酱油,学点没接触过的新东西吧,基本了解了下TreeView控件。

TreeView 控件用于在树结构中显示分层数据,例如目录或文件目录等。

下面看代码吧:

1.效果图

2.静态数据方式(即在页面上使用标签<asp:TreeNode>)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeViewTest.aspx.cs" Inherits="Yc_TestS.TreeViewTest" %>

<!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>TreeView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="treeT" runat="server">
<Nodes>
<asp:TreeNode NavigateUrl="#" Text="城市" Expanded="True">
<asp:TreeNode NavigateUrl="#" Text="北京市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="上海市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="天津市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="重庆市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="湖北省">
<asp:TreeNode NavigateUrl="#" Text="武汉市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="黄冈市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="荆州市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="武穴市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="十堰市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="黄石市"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="河北省">
<asp:TreeNode NavigateUrl="#" Text="石家庄市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="唐山市"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="山西省">
<asp:TreeNode NavigateUrl="#" Text="太原市"></asp:TreeNode>
<asp:TreeNode NavigateUrl="#" Text="大同市"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
</div>
</form>
</body>
</html>

TreeViewTest.aspx

3.前台数据源绑定方式

a.xml数据

<?xml version="1.0" encoding="utf-8" ?>
<Area iAreaID ="0" cAreaName="城市">
<Province iAreaID ="1" cAreaName="北京市"/>
<Province iAreaID ="2" cAreaName="上海市"/>
<Province iAreaID ="3" cAreaName="天津市"/>
<Province iAreaID ="4" cAreaName="重庆市"/>
<Province iAreaID ="5" cAreaName="湖北省">
<City iAreaID ="51" cAreaName="武汉市"/>
<City iAreaID ="52" cAreaName="黄冈市" />
<City iAreaID ="53" cAreaName="荆州市"/>
<City iAreaID ="54" cAreaName="武穴市" />
<City iAreaID ="55" cAreaName="十堰市"/>
<City iAreaID ="56" cAreaName="黄石市" />
</Province>
<Province iAreaID ="6" cAreaName="河北省">
<City iAreaID ="61" cAreaName="石家庄市"/>
<City iAreaID ="62" cAreaName="唐山市" />
</Province>
<Province iAreaID ="7" cAreaName="山西省">
<City iAreaID ="71" cAreaName="太原市" />
<City iAreaID ="72" cAreaName="大同市" />
</Province>
</Area>

Area.xml

b.前台页面(这里绑定了Xml的数据源)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeViewTest.aspx.cs" Inherits="Yc_TestS.TreeViewTest" %>

<!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>TreeView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%--TreeView控件的DataSourceID属性指定数据源控件源ID。--%>
<asp:TreeView ID="treeT" runat="server" DataSourceID="XmlDataSource1">
</asp:TreeView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Xml/Area.xml">
</asp:XmlDataSource>
</div>
</form>
</body>
</html>

TreeViewTest.aspx

c.后台代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using Yc_TestS.BaseClass; namespace Yc_TestS
{
public partial class TreeViewTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/**
* TreeNodeBinding类在TreeView控件中定义数据项与该数据项绑定到的节点之间的关系。
* 该类的DataMember属性指定在节点显示的数据源对应XML的节点。
* ValueField属性对应TreeNode对象的Value属性。
* TreeNodeBinding类的Text属性指定向用户显示的文本, 如果该属性没有指定,则默认与ValueField属性相同。
* */ this.treeT.ShowLines = false;//显示连接子节点和父节点之间的线条
TreeNodeBinding Area = new TreeNodeBinding();
Area.DataMember = "Area";//指定绑定的成员
Area.ValueField = "cAreaName";//取值的字段
this.treeT.DataBindings.Add(Area);
TreeNodeBinding Province = new TreeNodeBinding();
Province.DataMember = "Province";//添加与"省份"绑定
Province.ValueField = "cAreaName";
this.treeT.DataBindings.Add(Province);
TreeNodeBinding City = new TreeNodeBinding();
City.DataMember = "City";//添加与"城市"绑定
City.ValueField = "cAreaName";
this.treeT.DataBindings.Add(City); } }
}

TreeViewTest.aspx.cs

4.后台数据库数据填充方式

a.数据库数据

b.前台页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeViewTest.aspx.cs" Inherits="Yc_TestS.TreeViewTest" %>

<!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>TreeView</title>
<script type="text/javascript">
function show(msg) {
alert(msg);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="treeT" runat="server">
</asp:TreeView>
</div>
</form>
</body>
</html>

TreeViewTest.aspx

c.后台代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using Yc_TestS.BaseClass; namespace Yc_TestS
{
public partial class TreeViewTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AddTree(, null);
} private void AddTree(int Pid, TreeNode PNode)
{
string sqlStr = "SELECT Item_id,Item_name,Parent_ID FROM Para_item";
DataTable dt = YSqlHelper.ExecuteQuery(sqlStr, CommandType.Text);
if (dt.Rows.Count > )
{
DataView dv = new DataView(dt);
//过滤ParentID,得到当前的所有子节点 ParentID为父节点ID
dv.RowFilter = "[Parent_ID] = " + Pid;
//循环递归
foreach (DataRowView Row in dv)
{
//声明节点
TreeNode Node = new TreeNode();
//绑定超级链接
Node.NavigateUrl = String.Format("javascript:show('{0}')", Row["Item_Name"].ToString());
//开始递归
if (PNode == null)
{
//添加根节点
Node.Text = Row["Item_Name"].ToString();
treeT.Nodes.Add(Node);
Node.Expanded = true; //节点状态展开
AddTree(Int32.Parse(Row["Item_ID"].ToString()), Node); //再次递归
}
else
{
//添加当前节点的子节点
Node.Text = Row["Item_Name"].ToString();
PNode.ChildNodes.Add(Node);
Node.Expanded = true; //节点状态展开
AddTree(Int32.Parse(Row["Item_ID"].ToString()), Node); //再次递归
}
}
}
}
}
}

TreeViewTest.aspx.cs

d.配置文件

<?xml version="1.0"?>
<!--
有关如何配置 ASP.NET 应用程序的详细消息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration> <appSettings>
<add key="sqlStr" value="0dd8de75eb51766d66d42ead8ea26b0c533f6fdb009e9fd2e6e1c9867d2766ec499405047e4173a74015f57800e3afb982fd39d96dcc1590c8c943242992c84b "/>
</appSettings>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>

Web.config

e.两个助手类

using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text; namespace Yc_TestS.BaseClass
{
public class EntryCode
{
/// <summary>加密</summary>
public static string EncodeCode(string str)
{
string key = "david.yc";
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(, ));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(, ));
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, , bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString().Trim();
} /// <summary> Des 解密 GB2312 </summary>
public static string DecodeCode(string str)
{
string key = "david.yc";
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(, ));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(, ));
byte[] buffer = new byte[str.Length / ];
for (int i = ; i < (str.Length / ); i++)
{
int num2 = Convert.ToInt32(str.Substring(i * , ), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, , buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
return Encoding.GetEncoding("GB2312").GetString(stream.ToArray()).Trim();
}
}
}

加密和解密(EntryCode.cs)

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration; namespace Yc_TestS.BaseClass
{
public class YSqlHelper
{
private static string connectionString = EntryCode.DecodeCode(ConfigurationManager.AppSettings["sqlStr"]);//获取解密后的数据库连接字符串 /// <summary>执行不带参数的增删改SQL语句或存储过程</summary>
/// <param name="cmdText">增删改SQL语句或存储过程</param>
/// <param name="ct">命令类型</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(string cmdText, CommandType ct)
{
int res = ;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = ct;
res = cmd.ExecuteNonQuery();
}
}
catch
{ }
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
return res;
} /// <summary>执行带参数的增删改SQL语句或存储过程</summary>
/// <param name="cmdText">增删改SQL语句或存储过程</param>
/// <param name="ct">命令类型</param>
/// <returns>受影响的行数</returns>
public static int ExecuteNonQuery(string cmdText, SqlParameter[] paras, CommandType ct)
{
int res = ;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = ct;
cmd.Parameters.AddRange(paras);
res = cmd.ExecuteNonQuery();
}
}
catch
{ }
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
return res;
} /// <summary> 执行带参数的查询SQL语句或存储过程</summary>
/// <param name="cmdText">查询SQL语句或存储过程ì</param>
/// <param name="paras">参数集合?</param>
/// <param name="ct">命令类型</param>
/// <returns>DataTable对象</returns>
public static DataTable ExecuteQuery(string cmdText, CommandType ct)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = ct;
using (SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(sdr);
}
}
}
catch
{ }
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
return dt;
} /// <summary> 执行带参数的查询SQL语句或存储过程</summary>
/// <param name="cmdText">查询SQL语句或存储过程ì</param>
/// <param name="paras">参数集合?</param>
/// <param name="ct">命令类型</param>
/// <returns>DataTable对象</returns>
public static DataTable ExecuteQuery(string cmdText, SqlParameter[] paras, CommandType ct)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = ct;
cmd.Parameters.AddRange(paras);
using (SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(sdr);
}
}
}
catch
{ }
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
return dt;
} }
}

SQL数据库助手类(YSqlHelper.cs)

5.一些方法记录

a.控制父结点的开/合状态

TreeView_Tree.GetNodeFromIndex("1").Expanded=false/true;

b.清除某个父结点下的所有子节点

TreeView_IndexLeft.GetNodeFromIndex("1").Nodes.Clear();

c.设置所选节点,如选中第二个节点

function SetSelNode()  {   TreeView_Tree.selectedNodeIndex="1";  }

d.得到所选节点的Text,ID或NodeData

function GetAttribute()  {   alert(TreeView_Tree.getTreeNode(TreeView_Tree.selectedNodeIndex).getAttribute("Text"));  }

//替换Text为ID或NodeData,可分别得到所选节点的ID或NodeData

e.修改节点属性,如修改第一个节点的Text

function ModifyNode()  {   var node=TreeView_Tree.getTreeNode("0");   node.setAttribute("Text","第一个节点");  }

f.添加节点

function AddNode()  {   var node=TreeView_Tree.createTreeNode();   node.setAttribute("Text","第一个节点");   TreeView_Tree.add(node);      }

g.TreeView 中的SelectedIndexChange不执行

AutoPostBack=true,SelectedIndexChange才能被执行。

h.判断 TreeView 的一个节点下是否有子节点

if(SelectNode.Nodes.Count==0) {    //该节点没有字节点  }

【ASP.NET 进阶】TreeView控件学习的更多相关文章

  1. 【ASP.NET】TreeView控件学习

    相关链接 : http://www.cnblogs.com/yc-755909659/p/3596039.html

  2. 040. asp.netWeb中TreeView控件绑定XML文件

    xml文件格式: <?xml version="1.0" encoding="utf-8" ?> <sitemap title="进 ...

  3. asp.net动态添加控件学习

    看了老师的教程后,自己一点感悟记录下来: 1.在页面提交后,动态生成的控件会丢失, 但如果生成控件的代码在pageload中,就可以,原理是每次生成页面都执行生成. 2.动态按件或页面原来控件, 在页 ...

  4. duilib进阶教程 -- TreeView控件(6)

    代码下载:http://download.csdn.net/detail/qq316293804/6483905 上一个教程中,界面已经和迅雷一模一样啦,大小和位置一个像素都不差哟,亏得Alberl调 ...

  5. asp TreeView控件的使用

    相对于之前发过一个TreeView控件的使用方法 本次利用js操作,页面无刷新,性能提高 Css编码可能时我的模板页样式被继承下来,导致页面变乱,不需要的可以去掉 前台 <style> . ...

  6. 轻松学习Asp.net中的控件

    C/S 结构,即大家熟知的客户机和服务器结构.它是软件系统体系结构,通过它可以充分利用两端硬件环境的优势,将任务合理分配到Client端和Server端来实现,降低了系统的通讯开销.目前大多数应用软件 ...

  7. Winform控件学习-TreeView - ContextMenuStrip

    首先,要向窗体添加一个TreeView控件: 然后再添加一个ContextMenuStrip控件: 接下就要给TreeView添加一个MouseDown事件,代码如下: Example 1 priva ...

  8. Winform控件学习-TreeView

    转自 http://www.cnblogs.com/zxlovenet/p/3589425.html      作者: 初行 TreeView控件用来显示信息的分级视图,如同Windows里的资源管理 ...

  9. ASP.NET - TreeView控件,只操作最后一级节点

    效果: 使用母板页进行,左右页面进行跳转. 绑定TreeView控件:http://www.cnblogs.com/KTblog/p/4792302.html 主要功能: 点击节点的时候,只操作最后一 ...

随机推荐

  1. vue img标签图片加载时 闪烁

    //jsdata(){ return{ img_url: '', } },created(){ //请求数据,并给图片赋值url ajax.get(http_url) .then(res=>{ ...

  2. Mongodb条件查询Query的用法

    Query.All("name", "a", "b");//通过多个元素来匹配数组Query.And(Query.EQ("name ...

  3. C++进阶小结

    1.C++中类的不同存储区的对象的初始值 class test; class test { private: int i; int j; public: int geti() { return i; ...

  4. appium 元素文件 -查找元素 封装思路和方法

    方法1. try: target="//android.widget.TextView[@text='立即體驗']" element = WebDriverWait(dr,5,0. ...

  5. 学习笔记之Java

    Java (programming language) - Wikipedia https://en.wikipedia.org/wiki/Java_(programming_language) Ja ...

  6. 怎么把PNG图的位深度24位变成32位

    在PS里把图片的变成层模式,不透明度设置成99%,在保存成PNG

  7. 廖雪峰Java2面向对象编程-6Java核心类-6常用工具类

    1.Math Math提供了数学计算的静态方法 序号 方法 描述 1 abs() 返回参数的绝对值.Math.abs(-9)//9 2 ceil() 返回大于等于( >= )给定参数的的最小整数 ...

  8. [UE4]圆形小地图

    一.创建一个名为M_RoundRetainer的材质 二.创建一个名为RoundMiniMap的UserWidget 三.TestMiniMap中将添加进来 四.运行游戏

  9. SAS infile 导入txt示例

    概要说明: 以下代码包含的知识点: 1)ods 2)format picture 3)symputx ods pdf file="D:\fgroup\users\output\time.pd ...

  10. U3D学习06-数学基础

    1.fixed timestep 固定帧率, 2.time scale 快慢镜头,影响的是真实时间 3.time.deltatime增量时间,物体运动不受帧频率影响,每秒移动速度需要乘deltatim ...