ASP.net 将 SqlDataReader 转换为树
给定简单的数据结构:
ID | Category_Name | Parent_ID
示例:
1 Cars 0
2 Boxes 0
3 Lamborghinis 1
4 Camper Vans 1
5 Big Boxes 2
6 Small Boxes 2
7 Cereal Boxes 2
8 Broken Lambos 3
9 Yellow Ones 3
10 Rusty 8
11 Milkshake Stained 8
12 Chocolate Flavour 11
13 Strawberry 11
14 Indiscernible Solution 11
连同我的代码:
// Fetch current site setting
using (SqlCommand cmd = new SqlCommand("SELECT ID, catName, parentID FROM tblProductCats ORDER BY parentID ASC", cn))
{
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
// Fetch data
int catID = int.Parse(rdr[0].ToString());
string catName = rdr[1].ToString();
int catParent = int.Parse(rdr[2].ToString());
}
}
}
我需要将返回的数据转换为树结构,以便我可以通过它以漂亮的方式显示菜单!
我已经被困在这个问题上一段时间了,感谢任何帮助。
Given the simple data structure:
ID | Category_Name | Parent_ID
Example:
1 Cars 0
2 Boxes 0
3 Lamborghinis 1
4 Camper Vans 1
5 Big Boxes 2
6 Small Boxes 2
7 Cereal Boxes 2
8 Broken Lambos 3
9 Yellow Ones 3
10 Rusty 8
11 Milkshake Stained 8
12 Chocolate Flavour 11
13 Strawberry 11
14 Indiscernible Solution 11
Along with my code:
// Fetch current site setting
using (SqlCommand cmd = new SqlCommand("SELECT ID, catName, parentID FROM tblProductCats ORDER BY parentID ASC", cn))
{
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
// Fetch data
int catID = int.Parse(rdr[0].ToString());
string catName = rdr[1].ToString();
int catParent = int.Parse(rdr[2].ToString());
}
}
}
I need to convert that returned data into a tree structure so I can go through it displaying the menu in a pretty way!
I've been stuck on this for a while any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它看起来不像是最佳解决方案,但也许您可以在此 CodeProject 中找到一些灵感。
It doesn't look like an optimal solution, but maybe you can find some inspiration in this CodeProject.
看一下在 ASP.NET 中使用 TreeView 显示层次结构数据 。
Take a look at Display Hierarchical Data with TreeView in ASP.NET.
假设我们有一个类/结构类别,
现在,如果您的查询总是将类别的父级排序在其自身之前,那么您可以使用下面的代码,
因此 Tree 变量应该具有您的类别树。
Let's say we have a class/struct Category such that
Now, if your query always order category's parent before it self then you can use below code
So Tree variable should have your category tree.