如果不用从后台生成前台htm静态树,则树的速度有点慢,所以我把梅花树改了下:
梅花树的资料:开发文档: http://www.meizz.com/Web/Article.asp?id=436
控件下载: http://www.meizz.com/Web/Download/MzTreeView10.rar
应用示例: http://www.meizz.com/Web/Demo/MzTreeView10.htm
首先模板treetemplate.htm文件如下:
<HTML>
<HEAD>
<title>tree</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script language="JavaScript" src="MzTreeView10.js"></script>
<link href="menutree/menu.css" type="text/css" rel="stylesheet">
<style> A.MzTreeview { PADDING-LEFT: 3px; FONT-SIZE: 12px } </style>
</HEAD>
<body leftmargin="0" topmargin="2">
<SCRIPT LANGUAGE="JavaScript">
window.tree = new MzTreeView("tree");
tree.setIconPath("menutree/"); //可用相对路径
abcdefg
document.write(tree.toString()); //亦可用 obj.innerHTML = tree.toString();
//-->
</SCRIPT>
</body>
</HTML>
好了,下面是页面managertre.aspx的代码:
<%@ Page language="c#" Codebehind="managertree.aspx.cs" AutoEventWireup="false" Inherits="hualong.manager" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>管理中心</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<LINK href="style.css" type="text/css" rel="stylesheet">
<script language="javascript">
<!--
function ShowJie()
{
TianJia.style.display = "";
}
function window.onload()
{
if(arr=document.cookie.match(/scrollTop=([^;]+)(;|$)/))
document.body.scrollTop=parseInt(arr[1]);
}
function window.onbeforeunload(){
document.cookie="scrollTop="+document.body.scrollTop;
}
//-->
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<br>
<table cellSpacing="0" cellPadding="0" width="350" border="0">
<tr>
<td align="center" width="50%"><INPUT onclick="ShowJie();" type="button" value="添加节点"></td>
<td align="center"><asp:button id="btnTree" runat="server" Text="生成树"></asp:button></td>
</tr>
</table>
<table id="TianJia" style="DISPLAY: none; BORDER-COLLAPSE: collapse" borderColor="#6595d6"
cellSpacing="1" cellPadding="0" width="1000" align="center" border="1">
<tr>
<td align="center" width="60"><asp:button id="btnAddOk" runat="server" Text="添加"></asp:button></td>
<td align="center" width="50"><asp:textbox id="txtId" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="50"><asp:textbox id="txtParentId" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="120"><asp:textbox id="txtText" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="120"><asp:textbox id="txtHint" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="60"><asp:textbox id="txtIcon" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center"><asp:textbox id="txtData" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="150"><asp:textbox id="txtUrl" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="50"><asp:textbox id="txtTarget" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
<td align="center" width="120"><asp:textbox id="txtMethod" runat="server" Wrap="False" Width="100%"></asp:textbox></td>
</tr>
</table>
<TABLE id="Table1" cellSpacing="0" cellPadding="0" width="1000" align="center" border="0">
<TR>
<TD align="center" width="100%"><asp:datagrid id="dgTree" runat="server" Width="100%" DataKeyField="biaoshi_id" BorderWidth="1px"
BorderColor="#6595D6" AutoGenerateColumns="False">
<EditItemStyle Wrap="False"></EditItemStyle>
<ItemStyle Wrap="False"></ItemStyle>
<HeaderStyle Wrap="False" HorizontalAlign="Center" Height="30px" ForeColor="White" VerticalAlign="Middle"
BackColor="#6595D6"></HeaderStyle>
<Columns>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" HeaderText="管理" CancelText="取消" EditText="编辑">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="60px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
<FooterStyle Wrap="False"></FooterStyle>
</asp:EditCommandColumn>
<asp:ButtonColumn Text="删除" HeaderText="删除" CommandName="Delete">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="50px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:ButtonColumn>
<asp:BoundColumn DataField="ID" HeaderText="ID">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="50px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="parentId" HeaderText="父ID">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="50px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="text" HeaderText="节点文本">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="120px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="hint" HeaderText="节点提示">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="120px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="icon" HeaderText="节点图标">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="60px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="data" HeaderText="URL参数">
<HeaderStyle Wrap="False" HorizontalAlign="Center"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="url" HeaderText="URL">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="150px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="target" HeaderText="Target">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="50px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="method" HeaderText="Method">
<HeaderStyle Wrap="False" HorizontalAlign="Center" Width="120px"></HeaderStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:datagrid></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>
下面是后台managertree.aspx.cs后台文件:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace hualong
{
/// <summary>
/// manager 的摘要说明。
/// </summary>
public class manager : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnTree;
protected System.Web.UI.WebControls.TextBox txtId;
protected System.Web.UI.WebControls.TextBox txtParentId;
protected System.Web.UI.WebControls.Button btnAddOk;
protected System.Web.UI.WebControls.TextBox txtHint;
protected System.Web.UI.WebControls.TextBox txtIcon;
protected System.Web.UI.WebControls.TextBox txtData;
protected System.Web.UI.WebControls.TextBox txtUrl;
protected System.Web.UI.WebControls.TextBox txtTarget;
protected System.Web.UI.WebControls.TextBox txtMethod;
protected System.Web.UI.WebControls.TextBox txtText;
protected System.Web.UI.WebControls.DataGrid dgTree;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
BindData();
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnTree.Click += new System.EventHandler(this.btnTree_Click);
this.btnAddOk.Click += new System.EventHandler(this.btnAddOk_Click);
this.dgTree.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgTree_CancelCommand);
this.dgTree.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgTree_EditCommand);
this.dgTree.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgTree_UpdateCommand);
this.dgTree.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgTree_DeleteCommand);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void BindData()
{
string connString = ConfigurationSettings.AppSettings["connStr1"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand("select_treeview_pwqzc",conn);
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
dgTree.DataSource = comm.ExecuteReader();
dgTree.DataBind();
conn.Close();
}
private void dgTree_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
dgTree.EditItemIndex = e.Item.ItemIndex;
BindData();
}
private void dgTree_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
dgTree.EditItemIndex = -1;
BindData();
}
private void btnTree_Click(object sender, System.EventArgs e)
{
string str;//用他来包含所有树的节点信息
string connectstring = System.Configuration.ConfigurationSettings.AppSettings["connStr1"].ToString();
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectstring);
System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter("select_treeview_pwqzc",conn);
try
{
System.Text.StringBuilder node = new System.Text.StringBuilder();
conn.Open();
System.Data.DataSet dataset = new System.Data.DataSet();
dataset.Tables.Add("treeview");
adapter.Fill(dataset,"treeview");
foreach(System.Data.DataRow row in dataset.Tables[0].Rows)
{
node.Append("\r\n tree.nodes[\""+ row["parentId"].ToString() + "_" + row["id"] + "\"] = \"");
node.Append("text:" + row["text"].ToString().Replace("\0xE",";") + ";");
node.Append(row["hint"] != DBNull.Value && row["hint"].ToString() != string.Empty ? "hint:" + row["hint"].ToString().Replace("\0xE",";") + ";" : string.Empty);
node.Append(row["icon"] != DBNull.Value && row["icon"].ToString() != string.Empty ? "icon:" + row["icon"].ToString().Replace("\0xE",";") + ";" : string.Empty);
node.Append(row["data"] != DBNull.Value && row["data"].ToString() != string.Empty ? "data:" + row["data"].ToString().Replace("\0xE",";") +Server.UrlEncode(row["text"].ToString())+ ";" : string.Empty);
node.Append(row["url"] != DBNull.Value && row["url"].ToString() != string.Empty ? "url:" + row["url"].ToString().Replace("\0xE",";") + ";" : string.Empty);
node.Append(row["target"] != DBNull.Value && row["target"].ToString() != string.Empty ? "target:" + row["target"].ToString().Replace("\0xE",";") + ";" : string.Empty);
node.Append(row["method"] != DBNull.Value && row["method"].ToString() != string.Empty ? "method:" + row["method"].ToString().Replace("\0xE",";") + ";" : string.Empty);
node.Append("\"");
}
str = node.ToString();
dataset.Dispose();
}
finally
{
conn.Close();
}
StreamReader sr = new StreamReader(Server.MapPath(".")+"\\bbs\\treetemplate.htm",System.Text.Encoding.GetEncoding("gb2312"));//读取模板
string str1 = sr.ReadToEnd();
str1 = str1.Replace("abcdefg",str);//替换摸板里面的字符串
sr.Close();//关闭sr
StreamWriter sw = new StreamWriter(Server.MapPath(".")+"\\bbs\\left.htm",false,System.Text.Encoding.GetEncoding("gb2312"));//写入文件left.htm
sw.Write(str1);
sw.Flush();
sw.Close();
Response.Write("<script language=\"javascript\">alert('生成树成功!');</script>");
}
private void btnAddOk_Click(object sender, System.EventArgs e)
{
if(txtId.Text.Trim()=="" || txtParentId.Text.Trim()=="")
{
Page.RegisterStartupScript("","<script>alert('节点值与父节点值不能为空!而且只能够是整数!');document.getElementById('TianJia').style.display='';</script>");
return;
}
else
{
string connString = ConfigurationSettings.AppSettings["connStr1"].ToString();
SqlConnection conn = new SqlConnection(connString);
string selString = "select Count(id) from treeview where ID = @id";
SqlCommand comm = new SqlCommand(selString,conn);
comm.Parameters.Add(new SqlParameter("@id",SqlDbType.Int));
comm.Parameters["@id"].Value = Convert.ToInt32(txtId.Text.Trim());
conn.Open();
int i = (int)comm.ExecuteScalar();
conn.Close();
if(i>0)
{
Page.RegisterStartupScript("","<script>alert('已经存在相同ID值的节点,请重新输入!');document.getElementById('TianJia').style.display='';</script>");
return;
}
else
{
string insertString = "insert into treeview(ID,parentId,text,hint,icon,data,url,target,method) values(@ID,@parentId,@text,@hint,@icon,@data,@url,@target,@method)";
//插入数据库命令
SqlCommand comm1 = new SqlCommand(insertString,conn);
comm1.Parameters.Add(new SqlParameter("@ID",SqlDbType.Int));
comm1.Parameters.Add(new SqlParameter("@parentId",SqlDbType.Int));
comm1.Parameters.Add(new SqlParameter("@text",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@hint",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@icon",SqlDbType.VarChar,50));
comm1.Parameters.Add(new SqlParameter("@data",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@url",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@target",SqlDbType.VarChar,50));
comm1.Parameters.Add(new SqlParameter("@method",SqlDbType.VarChar,255));
//上面都是添加参数,下面是给参数赋值
comm1.Parameters["@ID"].Value = Convert.ToInt32(txtId.Text.Trim());
comm1.Parameters["@parentId"].Value = Convert.ToInt32(txtParentId.Text.Trim());
comm1.Parameters["@text"].Value = txtText.Text.Trim();
comm1.Parameters["@hint"].Value = txtHint.Text.Trim();
comm1.Parameters["@icon"].Value = txtIcon.Text.Trim();
comm1.Parameters["@data"].Value = txtData.Text.Trim();
comm1.Parameters["@url"].Value = txtUrl.Text.Trim();
comm1.Parameters["@target"].Value = txtTarget.Text.Trim();
comm1.Parameters["@method"].Value = txtMethod.Text.Trim();
conn.Open();
comm1.ExecuteNonQuery();//执行更新命令
conn.Close();
Response.Write("<script>alert('插入数据成功!');</script>");
BindData();//再次绑定数据
}
}
}
private void dgTree_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string connString = ConfigurationSettings.AppSettings["connStr1"].ToString();//连接数据库
SqlConnection conn = new SqlConnection(connString);
string delString = "delete from treeview where biaoshi_id=@biaoshi_id";//删除语句
SqlCommand comm = new SqlCommand(delString,conn);
comm.Parameters.Add(new SqlParameter("@biaoshi_id",SqlDbType.Int));//添加参数并且给参数赋值
comm.Parameters["@biaoshi_id"].Value = dgTree.DataKeys[e.Item.ItemIndex];//把单击删除按钮这行的主键值给参数赋值
conn.Open();
comm.ExecuteReader();//执行删除命令
conn.Close();
BindData();//重新绑定数据
}
private void dgTree_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//更新数据
string connString = ConfigurationSettings.AppSettings["connStr1"].ToString();//连接数据库
SqlConnection conn = new SqlConnection(connString);
//先看是不是有ID重复的节点
string selString = "select Count(*) from treeview where ID=@ID";
SqlCommand comm = new SqlCommand(selString,conn);
comm.Parameters.Add(new SqlParameter("@ID",SqlDbType.Int));//添加参数并且给参数赋值
comm.Parameters["@ID"].Value = Convert.ToInt32((e.Item.Cells[2].Controls[0] as TextBox).Text.Trim());//把单击更新按钮这行的ID值给参数赋值
conn.Open();
int i = (int)comm.ExecuteScalar();
conn.Close();
if(i>0)//如果存在相同的节点值
{
Page.RegisterStartupScript("","<script>alert('已经存在相同ID值的节点,请重新输入!');document.getElementById('TianJia').style.display='';</script>");
return;
}
else
{
string updateString = "update treeview set ID=@ID,parentId=@parentId,text=@text,hint=@hint,icon=@icon,data=@data,url=@url,target=@target,method=@method where biaoshi_id=@biaoshi_id";
//更新数据库命令
SqlCommand comm1 = new SqlCommand(updateString,conn);
comm1.Parameters.Add(new SqlParameter("@biaoshi_id",SqlDbType.Int));//添加参数并且给参数赋值
comm1.Parameters["@biaoshi_id"].Value = dgTree.DataKeys[e.Item.ItemIndex];//把单击删除按钮这行的主键值给参数赋值
comm1.Parameters.Add(new SqlParameter("@ID",SqlDbType.Int));
comm1.Parameters.Add(new SqlParameter("@parentId",SqlDbType.Int));
comm1.Parameters.Add(new SqlParameter("@text",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@hint",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@icon",SqlDbType.VarChar,50));
comm1.Parameters.Add(new SqlParameter("@data",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@url",SqlDbType.VarChar,255));
comm1.Parameters.Add(new SqlParameter("@target",SqlDbType.VarChar,50));
comm1.Parameters.Add(new SqlParameter("@method",SqlDbType.VarChar,255));
//上面都是添加参数,下面是给参数赋值
comm1.Parameters["@ID"].Value = Convert.ToInt32((e.Item.Cells[2].Controls[0] as TextBox).Text.Trim());
comm1.Parameters["@parentId"].Value = Convert.ToInt32((e.Item.Cells[3].Controls[0] as TextBox).Text.Trim());
comm1.Parameters["@text"].Value = (e.Item.Cells[4].Controls[0] as TextBox).Text.Trim();
comm1.Parameters["@hint"].Value = (e.Item.Cells[5].Controls[0] as TextBox).Text.Trim();
comm1.Parameters["@icon"].Value = (e.Item.Cells[6].Controls[0] as TextBox).Text.Trim();
comm1.Parameters["@data"].Value = (e.Item.Cells[7].Controls[0] as TextBox).Text.Trim();
comm1.Parameters["@url"].Value = (e.Item.Cells[8].Controls[0] as TextBox).Text.Trim();
comm1.Parameters["@target"].Value = (e.Item.Cells[9].Controls[0] as TextBox).Text.Trim();
comm1.Parameters["@method"].Value = (e.Item.Cells[10].Controls[0] as TextBox).Text.Trim();
conn.Open();
comm1.ExecuteNonQuery();//执行更新命令
conn.Close();
Response.Write("<script>alert('更新数据成功!');</script>");
dgTree.EditItemIndex = -1;//让编辑状态取消
BindData();//再次绑定数据
}
}
}
}
我在数据表中添加了一个字段biaoshi_id,他是标识列,自动递增.