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 ChubykinaComponents.Components { public partial class UserTreeView : UserControl { public UserTreeView() { 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 T? getSelecetedNodeValue() { if (treeView.SelectedNode == null || treeView.SelectedNode.Nodes.Count > 0) return default(T); TreeNode? node = treeView.SelectedNode; var type = typeof(T); var properties = type.GetProperties(); var item = Activator.CreateInstance(type); while (node != null) { var property = properties.FirstOrDefault(x => x.Name == node.Name); if (property != null) { property.SetValue(item, Convert.ChangeType(node.Text, property.PropertyType)); } node = node.Parent; } return item != null ? (T)item : default(T); } public void setHierarchy(List<(string, bool)> fields) { hierarchy = fields; } public void addItems(List items) { var type = typeof(T); var properties = type.GetProperties(); foreach (T item in items) { TreeNodeCollection nodes = treeView.Nodes; for (int i = 0; i < hierarchy.Count; i++) { var property = properties.FirstOrDefault(x => x.Name.Equals(hierarchy[i].Item1)); if (property is not null) { var node = nodes.Find(property.Name, false).FirstOrDefault(x => x.Text == property.GetValue(item).ToString()); if (node is not null && !hierarchy[i].Item2) { nodes = node.Nodes; } else { TreeNode newNode = nodes.Add(property.Name, property.GetValue(item).ToString()); nodes = newNode.Nodes; } } } } } public void clear() { treeView.Nodes.Clear(); } } }