创建一个组织机构类,包含Id,组织机构名称,父机构Id等属性,构建组织机构集合,通过TreeView控件显示组织机构,体现递归思想
时间: 2023-10-23 16:12:42 浏览: 73
好的,以下是一个示例代码:
首先,我们可以创建一个表示组织机构的类,例如:
```csharp
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public List<Organization> SubOrganizations { get; set; }
}
```
这个类有一个 id 属性、名称属性、父机构 id 属性和一个子组织机构列表属性,表示该组织机构的编号、名称、父机构编号和该组织机构的子机构列表。
接下来,我们可以创建一个组织机构集合类来管理所有的组织机构:
```csharp
public class OrganizationCollection
{
public List<Organization> Organizations { get; set; }
}
```
这个类有一个组织机构列表属性,表示所有的组织机构。
然后,我们可以使用这些类来构建组织机构集合,并且使用递归方式实现在 TreeView 控件中显示组织机构:
```csharp
private void PopulateTreeView(TreeView treeView, List<Organization> organizations, int parentId)
{
var nodes = organizations.Where(x => x.ParentId == parentId).ToList();
foreach (var node in nodes)
{
var treeNode = new TreeNode(node.Name)
{
Tag = node.Id
};
if (node.SubOrganizations.Any())
{
PopulateTreeView(treeNode, node.SubOrganizations);
}
treeView.Nodes.Add(treeNode);
}
}
private void PopulateTreeView(TreeNode parentNode, List<Organization> subOrganizations)
{
foreach (var subOrganization in subOrganizations)
{
var treeNode = new TreeNode(subOrganization.Name)
{
Tag = subOrganization.Id
};
if (subOrganization.SubOrganizations.Any())
{
PopulateTreeView(treeNode, subOrganization.SubOrganizations);
}
parentNode.Nodes.Add(treeNode);
}
}
private void Form1_Load(object sender, EventArgs e)
{
var organizationCollection = new OrganizationCollection();
var organization1 = new Organization
{
Id = 1,
Name = "Acme Inc.",
ParentId = 0,
SubOrganizations = new List<Organization>
{
new Organization
{
Id = 2,
Name = "Sales",
ParentId = 1,
SubOrganizations = new List<Organization>
{
new Organization
{
Id = 3,
Name = "North America",
ParentId = 2,
SubOrganizations = new List<Organization>()
},
new Organization
{
Id = 4,
Name = "Europe",
ParentId = 2,
SubOrganizations = new List<Organization>()
}
}
},
new Organization
{
Id = 5,
Name = "Marketing",
ParentId = 1,
SubOrganizations = new List<Organization>
{
new Organization
{
Id = 6,
Name = "Online",
ParentId = 5,
SubOrganizations = new List<Organization>()
},
new Organization
{
Id = 7,
Name = "Offline",
ParentId = 5,
SubOrganizations = new List<Organization>()
}
}
}
}
};
organizationCollection.Organizations = new List<Organization> { organization1 };
PopulateTreeView(treeView1, organizationCollection.Organizations, 0);
}
```
在这个示例中,我们创建了一个名为 "Acme Inc." 的组织机构,该组织机构有两个子机构:销售和市场营销。销售机构下面有北美和欧洲两个子机构,市场营销机构下面有在线和离线两个子机构。使用递归的方式,我们能够在 TreeView 控件中显示所有的组织机构层次关系。
阅读全文