转自:http://hi.baidu.com/wf225/blog/item/f0e25a6659f31924aa184c60.html
public System.Web.UI.WebControls.DropDownList AddDropDownList (System.Web.UI.WebControls.DropDownList droplist, int ParentID, ListItem plist)
{
string NodeId = "ID";
string ParentId = "ParentId";
string NodeName = "Name";
//DataSet dsFlowType = myData.GetFlowTypeDS();
DataView dvTree = new DataView(dsFlowType.Tables[0]);
//过滤ParentId,得到当前的所有子节点
dvTree.RowFilter = ParentId + " = " + ParentID.ToString();
foreach (DataRowView drv in dvTree)
{
//-----------------------------------------
int depth = 0;
int NodeID = Convert.ToInt32(drv[NodeId]); ;
Depth(NodeID, ref depth); //计算当前节点深度
string blank = "";
if (ParentID != 0)
{
for (int i = 1; i <= depth; i++)
{
blank += "|-";
}
}
//-----------------------------------------
ListItem list = new ListItem();
list.Text = blank + drv[NodeName].ToString().Trim();
list.Value = drv[NodeId].ToString().Trim();
droplist.Items.Add(list); //***注意区别:根节点
AddDropDownList(droplist, Int32.Parse(drv[NodeId].ToString().Trim()), list); //递归
}
return droplist;
}
//计算当前节点深度
public int Depth(int NodeID, ref int depth)
{
string NodeId = "ID";
string ParentId = "ParentId";
//DataSet dsFlowType = myData.GetFlowTypeDS();
DataView dvTree = new DataView(dsFlowType.Tables[0]);
//过滤ParentId,得到当前的所有父节点
dvTree.RowFilter = NodeId + " = " + NodeID.ToString();
foreach (DataRowView drv in dvTree)
{
int ID = Convert.ToInt32(drv[ParentId]);
if (ID != 0)
{
depth += 1;
Depth(ID, ref depth); //递归
}
}
return depth;
}