2011年9月13日 星期二
【ASP.NET】動態產生TREEVIEW
NoteId:節點代碼
ParnetId:父層節點代碼
sText:節點的Text
sValue:節點的Value
sURL:超鏈結
sTarget:超鏈結Target
updateName:資料修改者
updateTime:資料修改時間
//初始化
protected void InitTree()
{
TreeView Tree1 = new TreeView();
TreeNode tmpNode = new TreeNode();
tmpNode.Text = "首頁";
tmpNode.Value = "0";
tmpNode.NavigateUrl = "http://www.yahoo.com.tw";
tmpNode.Target = "_Top";
Tree1.Nodes.Add(tmpNode);
Session["Tree1"] = Tree1;
}
//建立Tree
protected void BuildTree()
{
TreeView Tree1 = new TreeView();
if (Session["Tree1"] == null)
{
InitTree();
}
Tree1 = (TreeView)Session["Tree1"];
TreeNode RootNode;
RootNode = Tree1.Nodes[0];
string rc;
rc = AddNodes(RootNode, 0);
Session["Tree1"] = Tree1;
}
protected void GetDataTable()
{
string ConnStr;
SqlConnection Conn;
SqlDataAdapter Da;
DataSet Ds;
DataTable dt;
string sqlTxt;
try
{
//取得web.config的連線字串
ConnStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnString"].ToString();
Conn = new SqlConnection(ConnStr);
Conn.Open();
sqlTxt = "Select * from tb_TreeView ";
Da = new SqlDataAdapter(sqlTxt, Conn);
Ds = new DataSet();
Da.Fill(Ds);
dt = new DataTable();
dt = Ds.Tables[0];
Session["dt"] = dt;
Conn.Close();
}
catch (Exception ex)
{
this.Label1.Text = ex.Message.ToString();
}
}
protected string AddNodes(TreeNode tNode, decimal PID)
{
try
{
if (Session["dt"] == null)
{
GetDataTable();
}
DataTable dt;
dt = (DataTable)Session["dt"];
DataRow[] rows;
string filterExpr;
filterExpr = "ParentId =" + PID;
rows = dt.Select(filterExpr);
if (rows.GetUpperBound(0) >=0)
{
DataRow row;
decimal tmpNodeId;
string tmpsText;
string tmpsValue;
string tmpsUrl;
string tmpsTarget;
TreeNode NewNode;
string rc;
for (int i = 0; i < rows.Length ; i++)
{
row = rows[i];
tmpNodeId = (decimal)row[0];
tmpsText = (string)row[2];
tmpsValue = (string)row[3];
tmpsUrl = (string)row[4];
tmpsTarget = (string)row[5];
NewNode = new TreeNode();
NewNode.Text = tmpsText;
NewNode.Value = tmpsText;
NewNode.NavigateUrl = tmpsUrl;
NewNode.Target = tmpsTarget;
tNode.ChildNodes.Add(NewNode);
rc = AddNodes(NewNode,tmpNodeId);
}
}
return "Success";
}
catch(Exception ex)
{
this.Label1.Text = ex.Message.ToString();
return "False";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Tree1"] == null)
{
InitTree();
BuildTree();
}
TreeView Tree1;
Tree1 = (TreeView)Session["Tree1"];
Tree1.ImageSet = TreeViewImageSet.XPFileExplorer;
this.PlaceHolder1.Controls.Add(Tree1);
}
轉載自 :http://tw.myblog.yahoo.com/jw!Iki8rGaBGAJfeU4uFKvazeLG8Mo-/article?mid=158&prev=184&next=52&l=f&fid=16&sc=1
訂閱:
張貼留言 (Atom)
謝謝分享!!
回覆刪除