C# 来自sql表的树视图
我有如下的sql表。我必须在树视图中显示它C# 来自sql表的树视图,c#,.net,asp.net,sql,treeview,C#,.net,Asp.net,Sql,Treeview,我有如下的sql表。我必须在树视图中显示它 id parentid name 1 NULL outlook 2 1 overcast 3 1 rainy 4 1 sunny 5 2 yes 6 3 wind 7 4 humidity 8 6 strong 9 6 weak 10 7 h
id parentid name
1 NULL outlook
2 1 overcast
3 1 rainy
4 1 sunny
5 2 yes
6 3 wind
7 4 humidity
8 6 strong
9 6 weak
10 7 high
11 8 no
12 9 yes
13 10 no
14 15 yes
15 7 normal
我希望输出为
-展望
- overcast
- yes
- rainy
- wind
- strong
- no
- weak
- yes
-sunny
- humidity
-high
-no
-normal
-yes
此处只有一个根节点“outlook”。然后出现类似的子节点和子节点。请在您的aspx或ascx文件中尝试以下代码:
WITH q AS
(
SELECT *
FROM mytable
WHERE ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
UNION ALL
SELECT m.*
FROM mytable m
JOIN q
ON m.parentID = q.ID
)
SELECT *
FROM q
<asp:Treeview ID="TreeView1" runat="server" />
或其他第三方工具,使这些类型的控件的数据绑定超级容易。树状视图的目的是仅当用户展开父节点时才显示子节点。换句话说,当父级展开时,您应该只加载直接子级。尝试在启动时加载所有树是一个糟糕的设计想法。这张桌子很小,所以这里没有什么大问题,但想象一下它是巨大的。为什么你要强迫你的用户等待一棵完整的树加载?@Jose Rui Santos先生,我是asp.net的初学者。我们可以在选择节点后进行节点扩展…,但我不知道怎么做…@Dhany;请将此行更改为ds.Relations.Add(“Children”、dtbl1.Columns[“Id”]、dtbl1.Columns[“ParentId”]);我刚才的回答可能会有所帮助:@CRice:在这段代码中,我将如何传递表数据。
private void PopulateTreeView()
{
DataSet ds = new DataSet(); //(populate the dataset with the table)
//Use LINQ to filter out items without a parent
DataTable parents = ds.Tables[0].AsEnumerable()
.Where(i => i.Field<object>("parentid") == DBNull.Value)
.CopyToDataTable();
//Use LINQ to filter out items with parent
DataTable children = ds.Tables[0].AsEnumerable()
.Where(i => i.Field<object>("parentid") != DBNull.Value)
.OrderBy(i => i.Field<int>("parentid"))
.CopyToDataTable();
//Add the parents to the treeview
foreach(DataRow dr in parents)
{
TreeNode node = new TreeNode();
node.Text = dr["name"].ToString();
node.Value = dr["id"].ToString();
TreeView1.Nodes.Add(node);
}
//Add the children to the parents
foreach(DataRow dr in children)
{
TreeNode node = new TreeNode();
node.Text = dr["name"].ToString();
node.Value = dr["id"].ToString();
TreeNode parentNode = FindNodeByValue(dr["parentid"].ToString());
if(parentNode != null)
parentNode.ChildNodes.Add(node);
}
}
private TreeNode FindNodeByValue(string value)
{
foreach(TreeNode node in TreeView1.Nodes)
{
if(node.Value = value) return node;
TreeNode pnode = FindNodeRecursion(node, value);
if(pnode != null) return pnode;
}
return null;
}
private TreeNode FindNodeRecursion(TreeNode parentNode, string value)
{
foreach(TreeNode node in parentNode.ChildNodes)
{
if(node.Value = value) return node;
TreeNode pnode = FindNodeRecursion(node, value);
if(pnode != null) return pnode;
}
return null;
}