99 lines
2.9 KiB
C#
99 lines
2.9 KiB
C#
|
using Library14Petrushin.Classes;
|
|||
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.ComponentModel;
|
|||
|
using System.Data;
|
|||
|
using System.Drawing;
|
|||
|
using System.Linq;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using System.Windows.Forms;
|
|||
|
|
|||
|
namespace Library14Petrushin
|
|||
|
{
|
|||
|
public partial class HierarchicalTreeView : UserControl
|
|||
|
{
|
|||
|
private List<string> hierarchy;
|
|||
|
private Dictionary<string, bool> alwaysNewBranch;
|
|||
|
|
|||
|
public HierarchicalTreeView()
|
|||
|
{
|
|||
|
InitializeComponent();
|
|||
|
hierarchy = new List<string>();
|
|||
|
alwaysNewBranch = new Dictionary<string, bool>();
|
|||
|
}
|
|||
|
|
|||
|
public void SetHierarchy(List<string> hierarchy, Dictionary<string, bool> alwaysNewBranch)
|
|||
|
{
|
|||
|
this.hierarchy = hierarchy;
|
|||
|
this.alwaysNewBranch = alwaysNewBranch;
|
|||
|
}
|
|||
|
|
|||
|
public void AddObjectToTree(object obj, string stopAtProperty)
|
|||
|
{
|
|||
|
TreeNode currentNode = treeView1.Nodes.Cast<TreeNode>().FirstOrDefault();
|
|||
|
foreach (var property in hierarchy)
|
|||
|
{
|
|||
|
var value = obj.GetType().GetProperty(property).GetValue(obj, null).ToString();
|
|||
|
bool createNewBranch = alwaysNewBranch.ContainsKey(property) && alwaysNewBranch[property];
|
|||
|
|
|||
|
if (currentNode == null)
|
|||
|
{
|
|||
|
currentNode = treeView1.Nodes.Add(value);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
var childNode = currentNode.Nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == value);
|
|||
|
if (childNode == null || createNewBranch)
|
|||
|
{
|
|||
|
childNode = currentNode.Nodes.Add(value);
|
|||
|
}
|
|||
|
currentNode = childNode;
|
|||
|
}
|
|||
|
|
|||
|
if (property == stopAtProperty)
|
|||
|
{
|
|||
|
break;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public int SelectedNodeIndex
|
|||
|
{
|
|||
|
get
|
|||
|
{
|
|||
|
return treeView1.SelectedNode?.Index ?? -1;
|
|||
|
}
|
|||
|
set
|
|||
|
{
|
|||
|
if (value >= 0 && value < treeView1.Nodes.Count)
|
|||
|
{
|
|||
|
treeView1.SelectedNode = treeView1.Nodes[value];
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public object GetSelectedObject()
|
|||
|
{
|
|||
|
if (treeView1.SelectedNode == null)
|
|||
|
{
|
|||
|
return null;
|
|||
|
}
|
|||
|
|
|||
|
var node = treeView1.SelectedNode;
|
|||
|
var obj = Activator.CreateInstance(typeof(Employee));
|
|||
|
foreach (var property in hierarchy)
|
|||
|
{
|
|||
|
var value = node.Text;
|
|||
|
obj.GetType().GetProperty(property).SetValue(obj, value);
|
|||
|
node = node.Parent;
|
|||
|
if (node == null)
|
|||
|
{
|
|||
|
break;
|
|||
|
}
|
|||
|
}
|
|||
|
return obj;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|