diff --git a/AbazovApp/AbazovAppView/FormTest.cs b/AbazovApp/AbazovAppView/FormTest.cs index ffb38e2..dbf6589 100644 --- a/AbazovApp/AbazovAppView/FormTest.cs +++ b/AbazovApp/AbazovAppView/FormTest.cs @@ -113,7 +113,7 @@ namespace AbazovAppView private void buttonGetValue_Click(object sender, EventArgs e) { - Worker? worker = abazovTreeView.getSelecetedNodeValue(); + Worker? worker = abazovTreeView.getSelecetedNodeValue(); if (worker == null) return; MessageBox.Show(worker.department + ", номер группы: " + worker.groupNumber + ", " + worker.name); } diff --git a/AbazovApp/AbazovViewComponents/Worker.cs b/AbazovApp/AbazovAppView/Worker.cs similarity index 100% rename from AbazovApp/AbazovViewComponents/Worker.cs rename to AbazovApp/AbazovAppView/Worker.cs diff --git a/AbazovApp/AbazovViewComponents/Components/AbazovTreeView.cs b/AbazovApp/AbazovViewComponents/Components/AbazovTreeView.cs index 956f8ae..5511527 100644 --- a/AbazovApp/AbazovViewComponents/Components/AbazovTreeView.cs +++ b/AbazovApp/AbazovViewComponents/Components/AbazovTreeView.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -using AbazovAppView; namespace AbazovViewComponents.Components { @@ -32,10 +31,43 @@ namespace AbazovViewComponents.Components } } - public Worker? getSelecetedNodeValue() + public T? 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); + if (treeView.SelectedNode == null || treeView.SelectedNode.Nodes.Count > 0) return default(T); + + List values = new List(); + List fieldNames = new List(); + + TreeNode? node = treeView.SelectedNode; + + var type = typeof(T); + var fields = type.GetFields(); + List types = new List(); + + while (node != null) + { + var field = fields.FirstOrDefault(x => x.Name == node.Name); + if (field != null) + { + Type typeOfField = field.FieldType; + types.Add(typeOfField); + values.Add(Convert.ChangeType(node.Text, typeOfField)); + fieldNames.Add(field.Name); + } + node = node.Parent; + } + + var constructor = type.GetConstructor(types.ToArray()); + if (constructor == null) return default(T); + var parameters = constructor.GetParameters(); + + List valuesForInvoking = new List(); + foreach (var param in parameters) + { + int index = fieldNames.IndexOf(param.Name); + valuesForInvoking.Add(values[index]); + } + return (T) constructor.Invoke(valuesForInvoking.ToArray()); } public void setHierarchy(List<(string, bool)> fields)