134 lines
3.7 KiB
C#
134 lines
3.7 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.ComponentModel;
|
||
using System.Data;
|
||
using System.Drawing;
|
||
using System.Linq;
|
||
using System.Reflection.Metadata.Ecma335;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using System.Windows.Forms;
|
||
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
||
|
||
namespace WinFormsLibrary
|
||
{
|
||
public partial class TreeClass : UserControl
|
||
{
|
||
private List<string> hierarchy;
|
||
public bool hasError = false;
|
||
|
||
public TreeClass()
|
||
{
|
||
InitializeComponent();
|
||
}
|
||
|
||
public void setHierarchy(List<string> h)
|
||
{
|
||
hierarchy = h;
|
||
}
|
||
|
||
private bool hasValue(TreeNodeCollection nodes, string value)
|
||
{
|
||
foreach (TreeNode node in nodes)
|
||
{
|
||
if (node.Text == value) return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private bool addData<T>(T t, string propertyName)
|
||
{
|
||
TreeNodeCollection current = treeView.Nodes;
|
||
TreeNode newNode = null;
|
||
|
||
foreach (string h in hierarchy)
|
||
{
|
||
if (h == propertyName)
|
||
{
|
||
var field = t.GetType().GetField(h);
|
||
|
||
if (field == null)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
string value = field.GetValue(t)?.ToString();
|
||
|
||
if (!hasValue(current, value))
|
||
{
|
||
newNode = current.Add(value); // Добавляем новый узел и сохраняем его в переменной newNode
|
||
}
|
||
return true;
|
||
}
|
||
else
|
||
{
|
||
// Аналогично добавляем новый узел и сохраняем его в переменной newNode
|
||
if (!hasValue(current, h))
|
||
{
|
||
newNode = current.Add(h);
|
||
}
|
||
else
|
||
{
|
||
// Находим существующий узел с нужным значением
|
||
foreach (TreeNode child in current)
|
||
{
|
||
if (child.Text == h)
|
||
{
|
||
newNode = child;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
current = newNode.Nodes; // Переходим к дочерним узлам нового узла
|
||
}
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
|
||
public bool setData<T>(T data, string propertyName)
|
||
{
|
||
bool status = addData<T>(data, propertyName);
|
||
if (!status) return false;
|
||
|
||
return true;
|
||
}
|
||
|
||
public T GetSelectedClass<T>() where T : new()
|
||
{
|
||
T res = default(T);
|
||
TreeNode node = treeView.SelectedNode;
|
||
|
||
if (node.Nodes.Count != 0)
|
||
{
|
||
hasError = true;
|
||
return res;
|
||
}
|
||
|
||
for (int i = hierarchy.Count - 1; i >= 0; i--)
|
||
{
|
||
if (node == null)
|
||
{
|
||
hasError = true;
|
||
return res;
|
||
}
|
||
|
||
var curr = res.GetType().GetField(hierarchy[i]);
|
||
if (curr == null)
|
||
{
|
||
hasError = true;
|
||
return res;
|
||
}
|
||
|
||
curr.SetValue(res, node.Text);
|
||
node = node.Parent;
|
||
}
|
||
|
||
return res;
|
||
}
|
||
}
|
||
}
|