COP-17/WinFormsProject/WinFormsLibrary/TreeClass.cs

134 lines
3.3 KiB
C#
Raw Permalink 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;
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;
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)) current.Add(value);
TreeNode elem = null;
foreach (TreeNode child in current)
{
if (child.Text == value)
{
elem = child;
break;
}
}
if (elem != null) current = elem.Nodes;
}
else
{
if (!hasValue(current, h)) current.Add(h);
TreeNode elem = null;
foreach (TreeNode child in current)
{
if (child.Text == h)
{
elem = child;
break;
}
}
if (elem != null) current = elem.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()
{
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;
}
}
}