转载:http://www.cnblogs.com/igoogleyou/archive/2012/12/17/treeview2.html
一,通过查询数据库的方法
ID 为主键,PID 表明数据之间的关系。
/// <summary>
/// 生产树的代码;
/// </summary>
/// <param name="node"> 根节点</param>
/// <param name="id">主键</param> private void CreateTwo(TreeNode node, int id)
{
string strSql = "select * from TableTest where PID = " + id;
DataTable dt = SqlClass.GetTable(strSql);
if (id == ) // id = 0 是根节点
{
for (int i = ; i < dt.Rows.Count; i++)
{
TreeNode nd = new TreeNode();
nd.Text = dt.Rows[i]["Name"].ToString();
CreateTwo(nd, Convert.ToInt32(dt.Rows[i]["id"].ToString()));
tvwTwo.Nodes.Add(nd);
}
}
else
{
for (int i = ; i < dt.Rows.Count; i++)
{
TreeNode Tnode = new TreeNode();
Tnode.Text = dt.Rows[i]["Name"].ToString();
CreateTwo(Tnode, Convert.ToInt32(dt.Rows[i]["id"].ToString()));
node.Nodes.Add(Tnode);
}
}
}
则个代码比较简单 只需要查询一个数据表。
不过会查询多次,我觉得不合适。
所以第二个方法,全部拿出来,在缓存里操作。
生成结果:
-------------------------------------------------------------------------------------------------------------------------------
二,通过linq 获取菜单的通用方法:
static void Main(string[] args)
{
//最终结果
UserR ur = new UserR();
//调用
Create(ur, );
//打印
Print(ur);
string str = JsonConvert.SerializeObject(ur);
Console.ReadLine();
}
//测试数据
static List<User> list = new List<User>()
{
new User(){id=,name="food",parentId=},
new User(){id=,name="fruit",parentId=},
new User(){id=,name="red",parentId=},
new User(){id=,name="cherry",parentId=},
new User(){id=,name="yellow",parentId=},
new User(){id=,name="banana",parentId=},
new User(){id=,name="meat",parentId=},
new User(){id=,name="beef",parentId=},
new User(){id=,name="pork",parentId=},
}; //递归遍历
private static void Create(UserR node, int id)
{
var q = list.Where(x => x.parentId == id).ToList();
for (int i = ; i < q.Count; i++)
{
UserR nd = new UserR();
nd.id = q[i].id;
nd.name = q[i].name;
Create(nd, q[i].id);
node.u.Add(nd);
} } //打印查看结果
static void Print(UserR ur)
{
Console.WriteLine(ur.name);
if (ur.u != null)
foreach (var item in ur.u)
{
Print(item);
}
} //查询出的实体层
public class User
{
public int id { get; set; }
public string name { get; set; }
public int parentId { get; set; }
}
//遍历后的实体层
public class UserR
{
public int id { get; set; }
public string name { get; set; }
public List<UserR> u = new List<UserR>();
public int parentId { get; set; }
}