COP-17/WinFormsProject/WinFormsLibrary/TreeClass.cs

134 lines
3.7 KiB
C#
Raw Normal View History

2023-10-04 22:43:22 +04:00
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
2023-11-02 11:29:09 +04:00
using System.Reflection.Metadata.Ecma335;
2023-10-04 22:43:22 +04:00
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;
2023-10-04 22:43:22 +04:00
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();
2023-10-04 22:43:22 +04:00
if (!hasValue(current, value))
2023-10-04 22:43:22 +04:00
{
2023-11-02 11:29:09 +04:00
newNode = current.Add(value); // Добавляем новый узел и сохраняем его в переменной newNode
}
2023-11-02 11:29:09 +04:00
return true;
2023-10-04 22:43:22 +04:00
}
else
{
// Аналогично добавляем новый узел и сохраняем его в переменной newNode
if (!hasValue(current, h))
{
newNode = current.Add(h);
}
else
2023-10-04 22:43:22 +04:00
{
// Находим существующий узел с нужным значением
foreach (TreeNode child in current)
2023-10-04 22:43:22 +04:00
{
if (child.Text == h)
{
newNode = child;
break;
}
2023-10-04 22:43:22 +04:00
}
}
current = newNode.Nodes; // Переходим к дочерним узлам нового узла
2023-10-04 22:43:22 +04:00
}
}
return true;
}
2023-10-04 22:43:22 +04:00
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()
{
2023-10-18 18:02:56 +04:00
T res = default(T);
2023-10-04 22:43:22 +04:00
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;
}
}
}