首先需要創建一個數據庫表test,字段包括nodeid、parentid、nodename、adderss、icon、linkurl
nodeid是在數據庫中作為節點的唯一標識,這里為了方便,將其設置為標識;
parentid表示每個節點的上級節點id,如該節點無上級,則為0;
nodename是節點在頁面上顯示的名稱;
以上三個字段應不能為空
adderss地址;icon節點圖片;linkurl節點鏈接地址;
以上三個字段用與不用不是必須的,因實際情況而定,這里因為使用到所以列出來
接著向設計窗體添加一個treeview控件
如果還沒添加過此控件的請到以下地址下載并安裝,添加引用microsoft.web.ui.webcontrols.dll然后到工具箱內添加控件
http://msdn.microsoft.com/archive/en-us/samples/internet/asp_dot_net_servercontrols/webcontrols/default.asp
下面是aspx.cs部分的代碼
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
using microsoft.web.ui.webcontrols;
namespace ioa
{
/// <summary>
/// webform1 的摘要說明。
/// </summary>
public class webform1 : system.web.ui.page
{
protected microsoft.web.ui.webcontrols.treeview treeview1;
protected classes.deptartment mydt=new ioa.classes.deptartment();//我把與數據庫鏈接以及對數據庫的操作請求寫在此類中
這里數據庫的鏈接就不具體寫出來了,鏈接數據庫以后
通過select * from test返回值傳給程序中的ds變
量即可,記得返回的值的類型是dataset
private void page_load(object sender, system.eventargs e)
{
inittreeview(this.treeview1.nodes);
// 在此處放置用戶代碼以初始化頁面
}
public void inittreeview(treenodecollection node)
{
this.inittree(node,"0");
}
public void inittree(treenodecollection nds,string parentid)
{
dataset ds=new dataset();
ds=mydt.treeinfo();
dataview dv = new dataview();
treenode tmpnd;
string intid;
dv.table = ds.tables[0];
dv.rowfilter = "parentid = " + parentid;
foreach(datarowview drv in dv)
{
tmpnd = new treenode();
tmpnd.id = drv["nodeid"].tostring();
if(drv["linkurl"].tostring().trim() != "")
{
tmpnd.text = "<a href ='"+drv["linkurl"].tostring().trim() +"'target='mainframe'>"+drv["nodename"].tostring()+"</a>";
}
else
{
tmpnd.text = drv["nodename"].tostring();
}
nds.add(tmpnd);
intid = drv["parentid"].tostring();
inittree(tmpnd.nodes,tmpnd.id);
}
}
#region web 窗體設計器生成的代碼
override protected void oninit(eventargs e)
{
//
// codegen: 該調用是 asp.net web 窗體設計器所必需的。
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void initializecomponent()
{
this.load += new system.eventhandler(this.page_load);
}
#endregion
}
}
新聞熱點
疑難解答
圖片精選