【发布时间】:2016-05-25 23:24:50
【问题描述】:
我使用的类的层次结构和关系可以这样可视化:
我也有用上面提到的关系写的相应的.cs类。
现在,我有以下列表:
List<Main_Subjects> msl = si.get_main_subjects().ToList();
List<Subject> sl = si.get_subjects().ToList();
List<Mini_subjects> mnsl = si.get_mini_subjects().ToList();
List<Text> tl = si.get_texts().ToList();
忽略 si.get... 语句。这些只是用来自 Web 服务的数据填充列表。这些列表充满了数据。
每个“Main_Subject”都有多个“Subject”。 每个“Subject”都有许多“Mini_Subject”。 每个“Mini_Subject”都有许多“Text”。
类的所有属性都设置为公开,因此您可以通过.property直接访问它们
我的目标是创建一个 TreeView 来查看我上面描述的层次结构,所以它看起来像这样:
main_subject.name
subject.name
mini_subject.name
text.name
text.name
subject.name
mini_subject.name
text.name
main_subject.name
subject.name
mini_subject.name
text.name
text.name
subject.name
mini_subject.name
text.name
text.name
不仅要在 TreeView 中存储名称,还要存储与查看的名称对应的对象。
层次结构是这样设置的:
1)Main_Subject
2)Subject
3)Mini_Subject
4)Text
我尝试创建嵌套的foreach 循环,但没有得到任何结果。
有什么建议吗?
编辑:
这是我到目前为止所拥有的,但它有问题: (忽略本地主机。声明。这些是因为 Web 服务而存在的)。
public void fill_tree()
{
int cnt = 0;
foreach (localhost.Main_Subjects a in msl)
{
treeView1.Nodes.Add(a.name);
treeView1.Nodes[cnt].Tag = a;
foreach (localhost.Subject b in sl)
{
if (b.main_subject_id == a.main_subject_id)
{
treeView1.Nodes[cnt].Nodes.Add(b.name);
treeView1.Nodes[cnt].Nodes[cnt].Tag = b;
foreach (localhost.Mini_subjects c in mnsl)
{
if (c.subject_id == b.subjects_id)
{
treeView1.Nodes[cnt].Nodes[cnt].Nodes.Add(c.name);
treeView1.Nodes[cnt].Nodes[cnt].Nodes[cnt].Tag = c;
foreach (localhost.Text d in tl)
{
if (d.mini_subjects_id == c.mini_subjects_id)
{
treeView1.Nodes[cnt].Nodes[cnt].Nodes[cnt].Nodes.Add(d.name);
treeView1.Nodes[cnt].Nodes[cnt].Nodes[cnt].Nodes[cnt].Tag = d;
}
}
}
}
}
}
cnt++;
}
}
错误:
System.Windows.Forms.dll 中出现“System.ArgumentOutOfRangeException”类型的未处理异常
附加信息:指定的参数超出范围 有效值。
【问题讨论】:
-
你试过使用子节点吗?
-
什么意思? @AlfieMcNarutoad
-
这里的问题是您在层次结构中的每个级别重用 cnt 索引 - 这是无效的,因为添加第二个根项目时不会存在第二个子项目。您需要在每个级别维护一个单独的索引,或者最好在处理每个级别时保留对每个节点的引用以避免重复索引。
-
引用每个节点是什么意思?具体如何?您可以添加示例代码吗? @BenJackson
-
抱歉耽搁了,请看下面的答案。