您的位置:首页 > 数据库

c#从数据库读取数据动态生成树形菜单

2015-07-31 09:00 716 查看
页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebTree.aspx.cs" Inherits="Tree.WebTree" %>

<!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>
<style>
body
{
background: #ecefff;
}
.navPoint
{
color: #666;
cursor: hand;
font-family: Webdings;
font-size: 9pt;
}
.NiuNiutree
{
width: 232px;
height: 525px;
overflow: auto;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="tvTree" runat="server" CssClass="NiuNiutree">
</asp:TreeView>
</div>
</form>
</body>
</html>

页面后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NewsDAL;
using System.Data;

namespace Tree
{
public partial class WebTree : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.tvTree.ShowLines = true;
this.tvTree.ShowExpandCollapse = true;
TreeNodeCollection tnc = new TreeNodeCollection();
tnc = this.tvTree.Nodes;
//0为根节点
GetTree(tnc, 0);
}
}

public void GetTree(TreeNodeCollection tnc, int parentID)
{
string sql = string.Format("SELECT [treeID],[prentID],[name] FROM [Tree].[dbo].[Tree] where prentID='{0}'", parentID);
DataTable dt = DBHeper.GetDataSet(sql);
foreach (DataRow dr in dt.Rows)
{
int treeid = Convert.ToInt32(dr["treeID"].ToString());
int prentID = Convert.ToInt32(dr["prentID"].ToString());
string name = Convert.ToString(dr["name"].ToString());
TreeNode tn = new TreeNode();
tn.Text = name;
tn.NavigateUrl = "javascript:getBoundary('" + name + "')";//调用前台js方法
tn.ImageUrl = "images/file.png";//默认图标为file.png
tnc.Add(tn);

int tncInt = dt.Rows.IndexOf(dr);
GetTree(tnc[tncInt].ChildNodes, treeid); //----------递归调用
}

if (dt.Rows.Count > 0)
{
tnc[0].Parent.ImageUrl = "images/openfoldericon.png";//设置父文件图标

}
else
{

tnc[0].Parent.ImageUrl = "images/file.png";
}

}

}
}

DBHeper:类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace NewsDAL
{

public static class DBHeper
{

private static SqlConnection connection;
/// <summary>
/// 连接数据库
/// </summary><returns>返回 SqlConnection 对象</returns>
public static SqlConnection Connection
{
get {
string connectionstring=ConfigurationManager.ConnectionStrings["conn"].ConnectionString.ToString();
if(connection==null)
{
connection = new SqlConnection(connectionstring);
connection.Open();
}
else if (connection.State== System.Data.ConnectionState.Closed)
{
connection.Open();
}
else if(connection.State==System.Data.ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
return DBHeper.connection;
}
}

//关闭数据库连接的方法

public static void CloesConnection()
{
try {
if(connection.State!=ConnectionState.Closed)
{
connection.Close();
}

}
catch(Exception e){

}

}

/// <summary>
/// 根据 SQL语句 查询所影响的行数
/// </summary>
/// <param name="sql"></param>
/// <returns>返回 int 类型</returns>
public static int ExecutCommand(string sql) {

try
{
SqlCommand cmd = new SqlCommand(sql,Connection);
int result = cmd.ExecuteNonQuery();
return result;

}catch(Exception e){
return 0;
}
}

/// <summary>
/// 根据 SQL语句、预编译数组 查询所影响的行数
/// </summary>
/// <param name="sql">参数 SQL 语句</param>
/// <param name="values">参数 预编译数组</param>
/// <returns>返回 int 类型</returns>

public static int ExecutCommand(string sql,params SqlParameter[] values) {
try
{
SqlCommand cmd = new SqlCommand(sql,Connection);
cmd.Parameters.Add(values);
int result = cmd.ExecuteNonQuery();
return result;

}
catch (Exception e)
{
return 0;
}

}

/// <summary>
/// 根据 SQL 语句查询得到的条数,执行查询,返回第一行第一列的值
/// </summary>
/// <param name="sql">参数 SQL 语句</param>
/// <returns>返回 int 类型</returns>
///
public static int GetScalar(string sql)
{
SqlCommand cmd = new SqlCommand(sql,Connection);
int result = Convert.ToInt32(cmd.ExecuteScalar());
return result;
}

/// <summary>
/// 根据 SQL语句、预编译数组 查询得到的条数,执行查询,返回第一行第一列的值
/// </summary>
/// <param name="sql">参数 SQL 语句</param>
/// <param name="values">参数 预编译数组</param>
/// <returns>返回 int 类型</returns>
public static int GetScalar(string sql,params SqlParameter[] values)
{
SqlCommand cmd = new SqlCommand(sql,Connection);
cmd.Parameters.AddRange(values);
int result = Convert.ToInt32(cmd.ExecuteScalar());//cmd.ExecuteScalar()返回的是一个Ojbect类型的
return result;
}

/// <summary>
/// 根据 SQL语句 查询数据
/// </summary>
/// <param name="sql">参数 接受一个 SQL语句</param>
/// <returns>返回 DataTable 类型</returns>
///
public static DataTable GetDataSet(string sql)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql,Connection);
SqlDataAdapter sda =new SqlDataAdapter(cmd);//sqlDataAdapter用于填充DataSet
sda.Fill(ds);//向DataTable中添加数据
return ds.Tables[0];//获得表的集合

}

/// <summary>
/// 根据 SQL语句、预编译数组 查询数据
/// </summary>
/// <param name="sql">参数 接受一个 SQL语句</param>
/// <param name="values">参数 接受一个 预编译数组</param>
/// <returns>返回 DataTable 类型</returns>
///

public static DataTable GetDataSet(string sql,params SqlParameter[] values) {

DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(sql,Connection);
cmd.Parameters.AddRange(values);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
return ds.Tables[0];
}
}

}

Web.config配置文件:
<?xml version="1.0"?>

<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 -->

<configuration>
<connectionStrings>
<add name="conn" connectionString="server=.;user=sa;pwd=alog;database=Tree"/>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

<system.web>
<compilation debug="true" targetFramework="4.0" />

<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>

<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>

<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>

<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>

</system.web>

<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

数据库:
USE [Tree]
GO
/****** Object: Table [dbo].[Tree] Script Date: 07/30/2015 18:22:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tree]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Tree](
[treeID] [int] IDENTITY(1,1) NOT NULL,
[prentID] [int] NOT NULL,
[name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Tree_1] PRIMARY KEY CLUSTERED
(
[treeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET IDENTITY_INSERT [dbo].[Tree] ON
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (1, 0, N'广州市')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (3, 1, N'天河区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (4, 1, N'越秀区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (5, 1, N'萝岗区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (6, 1, N'黄浦区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (7, 1, N'从化区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (8, 1, N'海珠区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (9, 3, N'车陂街道')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (10, 3, N'棠下街道')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (11, 3, N'石牌街道')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (12, 3, N'天园街道')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (13, 9, N'东圃社区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (14, 9, N'明珠新村社区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (15, 9, N'黄村社区')
INSERT [dbo].[Tree] ([treeID], [prentID], [name]) VALUES (16, 9, N'前进社区')
SET IDENTITY_INSERT [dbo].[Tree] OFF
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: