我有下面的表结构它可能不是一个正确的结构,但不幸的是,这是我给的。
id | Name | Parent | Status
1 First 0 Active
2 Child 1 Active
3 2Child 2 Inactive
逻辑:
Load Root by Parent = 0 and Status
OnPopulate根据父ID和状态为根后的每个级别加载子
我的问题是,如果状态是"非活动",我想看看哪些选项是非活动的,我不能,因为前两个选项是活动的。我需要的是能够在我的树视图查看所有的水平下降到选项,是不活动或活动。
我尝试了以下sql语句
select distinct
m.Id,
m.Name,
m.Parent,
m.[Status]
from mytable m
where m.Parent = 3 and m.[Status] = 'I'
union
select
Id,
Name,
Parent,
[Status]
from mytable
where ID in(select distinct
o.ID
from mytable o
where o.ID = 3 and o.[Status] = 'I') and Parent = 3
我已经用完了sql和编码的想法来弄清楚,希望有人能引导我在正确的方向,谢谢
也试过这个代码:
protected void mytree_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
//this is just a class that loads the values from db
MYList templist = new ListSyFamily();
templist.LoadAll();//(ddlStatus.SelectedValue, Convert.ToInt32(e.Node.Value));
foreach (temp temp in templist)
{
if (temp.Status == ddlStatus.SelectedValue && temp.Parent == Convert.ToInt32(e.Node.Value))
{
TreeNode child = new TreeNode();
child.Text = temp.Description;
child.Value = temp.Id.ToString();
if (child.ChildNodes.Count == 0)
child.PopulateOnDemand = true;
child.ToolTip = "Ver sub-opciones";
//child.SelectAction = TreeNodeSelectAction.SelectExpand;
child.CollapseAll();
e.Node.ChildNodes.Add(child);
}
}
}
我们是这样处理的
假设您有一个名为MyRecord的类来保存DB中的每一行数据:
public class MyRecord
{
public int Id {get; set; }
public int ParentId {get; set; }
public string Name { get; set; }
public string Status { get; set; }
// The children of this node
public MyRecordCollection Children = new MyRecordCollection();
}
然后你有一个集合类型来保存这些记录的id索引:
public class MyRecordCollection : System.Collections.Generic.Dictionary<int, MyRecord>
{
}
下面是预处理记录的代码(未显示从DB检索),然后将它们添加到树中:
MyRecordCollection cAllRecords;
MyRecordCollection cParentRecords = new MyRecordCollection();
// This is a method that just loads the records
cAllRecords = LoadAllRecords();
// Cycle through each of the records
foreach (MyRecord oRecord in cAllRecords.Values)
{
if (oRecord.Id == 0)
{
// If the record is a parent record, add it to the list of parents
cParentRecords.Add(oRecord.Id, oRecord);
}
else
{
// Otherwise, add the current record to its parent's list of children
cAllRecords[oRecord.ParentId].Children.Add(oRecord.Id, oRecord);
}
}
AddNodesToTree(cParentRecords, this.treeView1.Nodes);
最后,将记录添加到树中的递归方法:
/// <summary>
/// A recursive method to add all of the records to the specified collection of nodes
/// </summary>
/// <param name="cRecords"></param>
/// <param name="cNodes"></param>
private void AddNodesToTree(MyRecordCollection cRecords, TreeNodeCollection cNodes)
{
foreach (MyRecord oRecord in cRecords.Values)
{
TreeNode oNode = new TreeNode();
oNode.Text = oRecord.Name;
oNode.Tag = oRecord;
cNodes.Add(oNode);
// Now add the node's children if any
if (oRecord.Children.Count != 0)
{
AddNodesToTree(oRecord.Children, oNode.Nodes);
}
}
}
嗯,如果我是你,我会把整个表加载到内存中,放入一个简单的DTO类的集合中,然后用c#计算出你的树视图。这似乎比在SQL中尝试大量选项要容易得多。