PIbd-33_Abazov_A.A._KOP_29/AbazovApp/AbazovViewComponents/Components/AbazovTreeView.cs
2023-09-21 21:05:38 +04:00

74 lines
2.5 KiB
C#

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 AbazovAppView;
namespace AbazovViewComponents.Components
{
public partial class AbazovTreeView : UserControl
{
public AbazovTreeView()
{
InitializeComponent();
}
private List<(string, bool)> hierarchy = new List<(string, bool)>();
public int SelectedNodeIndex
{
get
{
return treeView.SelectedNode?.Index ?? -1;
}
set
{
if (treeView.SelectedNode == null) treeView.SelectedNode = value >= 0 && value < treeView.Nodes.Count ? treeView.Nodes[value] : treeView.SelectedNode;
else treeView.SelectedNode = value >= 0 && value < treeView.SelectedNode.Nodes.Count ? treeView.SelectedNode.Nodes[value] : treeView.SelectedNode;
}
}
public Worker? getSelecetedNodeValue()
{
if (treeView.SelectedNode == null || treeView.SelectedNode.Nodes.Count > 0) return null;
return new Worker(treeView.SelectedNode.Parent.Parent.Text, Convert.ToInt32(treeView.SelectedNode.Parent.Text), treeView.SelectedNode.Text);
}
public void setHierarchy(List<(string, bool)> fields)
{
hierarchy = fields;
}
public void addItems<T>(List<T> items)
{
var type = typeof(T);
var fields = type.GetFields();
foreach (T item in items)
{
TreeNodeCollection nodes = treeView.Nodes;
for (int i = 0; i < hierarchy.Count; i++)
{
var field = fields.FirstOrDefault(x => x.Name.Equals(hierarchy[i].Item1));
if (field is not null)
{
var node = nodes.Find(field.Name, false).FirstOrDefault(x => x.Text == field.GetValue(item).ToString());
if (node is not null && !hierarchy[i].Item2)
{
nodes = node.Nodes;
}
else
{
TreeNode newNode = nodes.Add(field.Name, field.GetValue(item).ToString());
nodes = newNode.Nodes;
}
}
}
}
}
}
}