PIbd-32_Artamonova_T.V._COP_2/COP/UserTreeView.cs

104 lines
3.3 KiB
C#
Raw Normal View History

2023-10-12 18:40:10 +04:00
using System.Xml;
namespace COP
{
public partial class UserTreeView : UserControl
{
private event Action? _errorOccured;
public List<string> Hierarchy;
public string Error { get; private set; }
public UserTreeView()
{
InitializeComponent();
Error = string.Empty;
Hierarchy = new();
}
// иерархия
// метод заполнения иерархии
public event Action AnErrorOccurred
{
add { _errorOccured += value; }
remove { _errorOccured -= value; }
}
public int SelectedItemIndex
{
get
{
if (treeView.SelectedNode == null)
{
return -1;
}
return treeView.SelectedNode.Index;
}
}
public T? GetSelectedObject<T>() where T : class, new()
{
// параметризованный
//проверка есть или нет иерархии
TreeNode selectedNode = treeView.SelectedNode;
if (Hierarchy == null)
{
throw new Exception("Hierarchy is not set.");
}
if (selectedNode?.FirstNode != null)
{
throw new Exception("Not a last level node.");
}
T currentBranch = new T();
Hierarchy.Reverse();
foreach (var property in Hierarchy)
{
typeof(T).GetProperty(property).SetValue(currentBranch, Convert.ChangeType(selectedNode.Text, typeof(T).GetProperty(property).PropertyType));
selectedNode = selectedNode.Parent;
}
Hierarchy.Reverse();
return currentBranch;
}
//проверка что выбранный элем последний в ветке
2023-10-28 09:06:35 +04:00
public void PopulateTree<T>(List<T> items, List<string> Hierarchy)
2023-10-12 18:40:10 +04:00
{
treeView.BeginUpdate();
treeView.Nodes.Clear();
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
if (Hierarchy == null)
{
throw new Exception("Hierarchy is not set.");
}
foreach (var item in items)
{
TreeNodeCollection treeViewNodes = treeView.Nodes;
foreach (var elem in Hierarchy)
{
bool flag = false;
for (int i = 0; i < treeViewNodes.Count; i++)
{
if (item.GetType().GetProperty(elem).GetValue(item).ToString() == treeViewNodes[i].Text)
{
treeViewNodes = treeViewNodes[i].Nodes;
flag = true;
break;
}
}
if (!flag)
{
var newNode = treeViewNodes.Add(item.GetType().GetProperty(elem).GetValue(item).ToString());
treeViewNodes = newNode.Nodes;
}
}
}
treeView.EndUpdate();
}
}
}