下面的例子將結合項目實際運用來使用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);
}
}
}
}