下面的例子將結合項目實際運用來使用Jquery.TreeView,當然在使用控件樹需要現在相應的js文件
下面就把我生成的TreeView展現給大家看看希望對大家有所幫助!在使用之前需要下載控件樹的js文件和Css樣式
介紹一下表結構
M_ID M_Name M_ParentID M_URL M_Sort
然後新建一個網站,在新建的網站下添加CSS文件夾和js文件夾分別用於存放Css樣式和JS,同時再添加一個image文件夾用於存放TreeView的圖片
接著我們就開始實現我們的功能了!
前台代碼
代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<link rel="stylesheet" href="CSS/screen.css" />
<link rel="Stylesheet" href="CSS/jquery.treeview.css" />
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script src="js/jquery.treeview.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#tree").treeview();
})
</script>
</head>
<body>
<div id="main">
<a>Main Demo</a>
<div id="sidetree">
<ul id="tree" runat="server">
</ul>
</div>
</div>
</body>
</html>
後台代碼:
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = getDate();
createmenu(ds, null, tree);
}
}
public DataSet getDate()
{
DataSet ds = new DataSet();
string config = System.Configuration.ConfigurationManager.ConnectionStrings["LiveOffice"].ToString();
SqlConnection conn = new SqlConnection(config);
SqlDataAdapter da = new SqlDataAdapter("select * from SystemMenu order by M_Sort", conn);
da.Fill(ds);
return ds;
}
private void createmenu(DataSet ds, string parentId, HtmlGenericControl UL)
{
DataRow[] rows;
if (string.IsNullOrEmpty(parentId))
rows = ds.Tables[0].Select("M_ParentID is null");//過濾
else
rows = ds.Tables[0].Select("M_ParentID='" + parentId + "'");//過濾
foreach (DataRow t in rows)
{
DataRow[] childern = ds.Tables[0].Select("M_ParentID =" + t["M_ID"].ToString());//用於判斷是否有子節點
HtmlGenericControl serverLi = new HtmlGenericControl("li");//生成Li標簽,作為父節點
if (childern.Length != 0 || parentId == "")//是父節點
{
serverLi.InnerText = t["M_name"].ToString();
HtmlGenericControl serverUL = new HtmlGenericControl("ul");
serverLi.Controls.Add(serverUL);
UL.Controls.Add(serverLi);
createmenu(ds, t["M_ID"].ToString(), serverUL);
}
else
{
//生成標簽a
HtmlAnchor NewAnchorControl = new HtmlAnchor();
// 設置標簽a的屬性
NewAnchorControl.Name = "NewAnchorControl";
NewAnchorControl.InnerHtml = t["M_Name"].ToString();
NewAnchorControl.HRef = t["M_URL"].ToString();
NewAnchorControl.Target = "_black";//設置顯示的位置,這裡改一下
serverLi.Controls.Add(NewAnchorControl);
UL.Controls.Add(serverLi);
createmenu(ds, t["M_ID"].ToString(), UL);
}
}
}
}