以下是前两周的新知识,主要是treeview控件的学习和应用,其中有一位哥们的贴子被我仔细分析了一下,但是还是没有完全看明白,不过为我学习treeview开拓了思路,不错,再次发上来让大家共享。
----------------------------------------
由底向上按层次(深度)遍历法生成树算法
l Step 0:数据准备,给定数据集(TagValue,ContentValue,DepthID), TagValue是节点的实际值,ContentValue是节点显示的值或者说标签值,DepthID是节点的深度编号。若节点为根节点,一般其DepthID长度为最短。给定最大深度iMaxDepLen和最小深度iMinDepLen。给定用于存储当前子树的Hashtable;
l Step 1:给定当前遍历的层级长度iCurDepLen,初始设为iMaxDepLen;
l Step 2:在数据集中根据给定iCurDepLen查找满足条件的层级,得到该层级的节点集objArr[],
if (objArr == null)
return;
else
{
//遍历节点集
for(int i=0; i<objArr.Length;i++)
{
Step 2.1 查找objArr[i]的父节点,若无父节点,直接加入,goto Step 2.2;若有父节点,先查找父节点是否已在Hashtable中。若有,将其从Hashtable中移出并记为tempParNode;否则生成新节点tempParNode;goto Step 2.3;
Step 2.2 若当前节点objArr[i]不在Hashtable中,在Hashtable中添加objArr[i];continue;
Step 2.3 若当前节点objArr[i]不在Hashtable中,根据objArr[i]生成节点tempNode;否则,将其从Hashtable中移出,并记为tempNode;将tempNode插到tempParNode中,并将存入Hashtable。
}
}
l Step 3:若当前层级iCurDepLen大于最小层级iMinDepLen,则继续回溯,将iCurDepLen减1并作为当前iCurDepLen,goto Step 2;否则goto Step 4.
l Step 4:在得到用Hashtable存储的节点表后(实际上是一子树表),遍历Hashtable,将各棵子树插入TreeView.
---------------------------------------------
虽然我已经明白该兄的想法,但是我觉得我自己还是无法用代码实现。以下是我自己的实现方式,但这种方法的缺陷是如果有一个子节点有权限那么该节点的父节点必须选择。
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
string sel="select * from wl_catalog";
myconn.Open();
SqlDataAdapter da=new SqlDataAdapter(sel,myconn);
DataSet ds=new DataSet();
da.Fill(ds);
this.ViewState["ds"]=ds;
myconn.Close();
addtreenode(0,(TreeNode)null);
}
}
#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
private void addtreenode(int parentid,TreeNode pNode)
{
DataSet ds=(DataSet)this.ViewState["ds"];
DataView dvtree=new DataView(ds.Tables[0]);
dvtree.RowFilter="[parentid]="+parentid;
foreach(DataRowView Row in dvtree)
{
TreeNode Node=new TreeNode();
if(pNode==null)
{
Node.Text=Row["Catalogname"].ToString();
TreeView1.Nodes.Add(Node);
Node.Expanded=false;
addtreenode(Convert.ToInt32(Row["id"].ToString()),Node);
}
else
{
if((getpower().IndexOf(Row["id"].ToString()))!=-1)
{
Node.Text=Row["Catalogname"].ToString();
Node.NavigateUrl=Row["typeurl"].ToString();
pNode.Nodes.Add(Node);
Node.Expanded=false;
}
addtreenode(Convert.ToInt32(Row["id"].ToString()),Node);
}
}
}
private string getpower()
{
string sel="select perview from wl_role where id='"+Convert.ToInt32(Session["roleid"].ToString())+"'";
SqlCommand mycommand=new SqlCommand(sel,myconn);
myconn.Open();
SqlDataReader dr=mycommand.ExecuteReader();
if(dr.Read())
{
power=dr["perview"].ToString();
}
dr.Close();
myconn.Close();
return power;
}