效果图:
ASPX代码:
<asp:DropDownList ID="drpZhiWutSort" runat="server"></asp:DropDownList>
C#代码:
using (LeaderTripDataContext db = new LeaderTripDataContext())
{
var getSoStatus = from p in db.ZhiWuList where p.isshow=='Y' select new { p.menuid, p.menuname, p.fathermenuid, p.isshow };
if (getSoStatus.Count() <= 0)
{
ZhiWuList insert = new ZhiWuList { menuname = "公司职务", fathermenuid = -1, sortid = 1,isshow='Y', addTime = DateTime.Now };
db.ZhiWuList.InsertOnSubmit(insert);
db.SubmitChanges();
}
DataTable dtSort = SearchDataClass.ToDataTable(getSoStatus);
//添加根目录
DataRow[] drs = dtSort.Select("fathermenuid=-1");
for (var i = 0; i < drs.Length; i++)
{
string nodeid = drs[i]["menuid"].ToString();
string text = drs[i]["menuname"].ToString();
text = "╋" + text;
this.drpZhiWutSort.Items.Add(new ListItem(text, nodeid));
int sonparentid = int.Parse(nodeid);
addOtherDll("", sonparentid, dtSort, 1, drpZhiWutSort);
}
drpZhiWutSort.DataBind();
drpZhiWutSort.Items.Insert(0, new ListItem("-请选择职务-"));
}
}
addOtherDll 引用的方法:
//<param name="Pading">空格</param>
//<param name="DirId">父路径ID</param>
//<param name="datatable">返回的datatable</param>
//<param name="deep">树形的深度</param>
public static void addOtherDll(string Pading, int DirId, DataTable datatable, int deep, DropDownList ddl)
{
DataRow[] rowlist = datatable.Select("fathermenuid='" + DirId + "'");
foreach (DataRow row in rowlist)
{
string strPading = "";
for (int j = 0; j < deep; j++)
{
strPading += " "; //用全角的空格
}
//添加节点
ListItem li = new ListItem(strPading + "|--" + row["menuname"].ToString(), row["menuid"].ToString());
ddl.Items.Add(li);
//递归调用addOtherDll函数,在函数中把deep加1
addOtherDll(strPading, Convert.ToInt32(row["menuid"]), datatable, deep + 1, ddl);
}
}