Advertisement
Guest User

ItemForm

a guest
Feb 25th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.05 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Windows.Forms;
  7. using System.Reflection;
  8.  
  9. namespace OOP_UI
  10. {
  11.     public partial class ItemForm : Form
  12.     {
  13.         private Cosmetics pCosmetics;
  14.         private List<Cosmetics> pCosmeticsList;
  15.  
  16.         const int formWidth = 500;
  17.         const int formMinHeight = 60;
  18.         const int fieldHeight = 25;
  19.  
  20.         const int paddingLeft = 15;
  21.         const int paddingUp = 25;
  22.  
  23.         const int SpaceBetweenLabelAndBox = 30;
  24.  
  25.         public ItemForm(Cosmetics Cosmetic, List<Cosmetics> CosmeticsList)
  26.         {
  27.             //список всех полей объекта
  28.             FieldInfo[] fields = Cosmetic.GetType().GetFields();
  29.  
  30.             //получение имени формы
  31.             string fieldName = Cosmetic.GetType().ToString();
  32.  
  33.             //если у экземляра класса имеется атрибут с названием, то форма будет иметь соответствующее имя
  34.             object[] attributes = Cosmetic.GetType().GetCustomAttributes(typeof(InfoAttribute), inherit: true);
  35.             if (attributes.Length != 0)
  36.             {
  37.                 InfoAttribute myAttr = (InfoAttribute)attributes[0];
  38.                 fieldName = myAttr.Name;
  39.             }
  40.  
  41.             //создание пустой формы для редактирования полей
  42.             base.Text = fieldName;
  43.             base.Size = new System.Drawing.Size(formWidth, formMinHeight + fieldHeight * (fields.Length + 2));
  44.             base.MaximizeBox = false;
  45.  
  46.             //создание полей
  47.             for (int i = 0; i < fields.Length; i++)
  48.             {
  49.                 //получение имени для Label
  50.                 fieldName = fields[i].GetType().ToString();
  51.  
  52.                 //если у поля имеется атрибут с названием, то форма будет иметь соответствующее имя
  53.                 attributes = fields[i].GetCustomAttributes(typeof(InfoAttribute), true);
  54.                 if (attributes.Length != 0)
  55.                 {
  56.                     InfoAttribute myAttr = (InfoAttribute)attributes[0];
  57.                     fieldName = myAttr.Name;
  58.                 }
  59.  
  60.                 //надпись содержащая тип и имя поля
  61.                 Label label = new Label
  62.                 {
  63.                     Location = new Point(paddingLeft, paddingUp * (i + 1)),
  64.                     Width = base.Width / 2,
  65.                     Text = fieldName
  66.                 };
  67.  
  68.                 base.Controls.Add(label);
  69.  
  70.                 //1  можно использовать рефакторинг
  71.                 //Создание для стандартных типов значений текстовых полей ввода, и их заполнение
  72.                 if (fields[i].FieldType == typeof(bool))
  73.                 {
  74.                     base.Controls.Add(MakeCheckBox(fields, Cosmetic, label, i));
  75.                 }
  76.                 else if (((fields[i].FieldType.IsPrimitive) && (!fields[i].FieldType.IsEnum))
  77.                         || (fields[i].FieldType == typeof(string)))
  78.                 {
  79.                     base.Controls.Add(MakeTextBox(fields, Cosmetic, label, i));
  80.                 }
  81.  
  82.                 //Создание выпадающих списков для перечислимых типов
  83.                 else if (fields[i].FieldType.IsEnum)
  84.                 {
  85.                     base.Controls.Add(MakeEnumBox(fields, Cosmetic, label, i));
  86.                 }
  87.  
  88.                 //Создание выпадающих списков для вложенных членов
  89.                 else if ((!fields[i].FieldType.IsPrimitive) && (!fields[i].FieldType.IsEnum) && (!(fields[i].FieldType == typeof(string))))
  90.                 {
  91.                     base.Controls.Add(MakeObjectBox(fields, Cosmetic, CosmeticsList, label, i));
  92.                 }
  93.                 //1
  94.             }
  95.  
  96.             //кнопка сохранения
  97.             Button SaveBut = new Button
  98.             {
  99.                 Name = "SaveBut",
  100.                 Text = "Save",
  101.                 Location = new Point(base.Width / 2 - (base.Width / 8), (fields.Length + 1) * (fieldHeight + 1)),
  102.                 Width = base.Width / 4,
  103.                 DialogResult = DialogResult.OK,
  104.             };
  105.  
  106.             pCosmetics = Cosmetic;
  107.             pCosmeticsList = CosmeticsList;
  108.             SaveBut.Click += SaveAction;
  109.  
  110.             base.Controls.Add(SaveBut);
  111.         }
  112.  
  113.         private CheckBox MakeCheckBox(FieldInfo[] qfields, Cosmetics qCosmetic, Label qlabel, int i)
  114.         {
  115.             CheckBox check = new CheckBox()
  116.             {
  117.                 Name = qfields[i].Name,
  118.                 Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
  119.                 Checked = (bool)qfields[i].GetValue(qCosmetic)
  120.             };
  121.  
  122.             return check;
  123.         }
  124.  
  125.         private TextBox MakeTextBox(FieldInfo[] qfields, Cosmetics qCosmetic, Label qlabel, int i)
  126.         {
  127.             TextBox textBox = new TextBox
  128.             {
  129.                 Name = qfields[i].Name,
  130.                 Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
  131.                 Width = base.Width - (qlabel.Location.X + qlabel.Width + SpaceBetweenLabelAndBox),
  132.                 Text = qfields[i].GetValue(qCosmetic).ToString()
  133.             };
  134.  
  135.             return textBox;
  136.         }
  137.  
  138.         private ComboBox MakeEnumBox(FieldInfo[] qfields, Cosmetics qCosmetic, Label qlabel, int i)
  139.         {
  140.             ComboBox comboBox = new ComboBox
  141.             {
  142.                 Name = qfields[i].Name,
  143.                 SelectionStart = 0,
  144.                 DropDownStyle = ComboBoxStyle.DropDownList,
  145.                 Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
  146.                 Width = base.Width - (qlabel.Location.X + qlabel.Width + SpaceBetweenLabelAndBox)
  147.             };
  148.  
  149.             comboBox.Items.AddRange(qfields[i].FieldType.GetEnumNames());
  150.             comboBox.SelectedIndex = (int)(qfields[i].GetValue(qCosmetic));
  151.  
  152.             return comboBox;
  153.         }
  154.  
  155.         private ComboBox MakeObjectBox(FieldInfo[] qfields, Cosmetics qCosmetic, List<Cosmetics> qCosmeticsList, Label qlabel, int i)
  156.         {
  157.             ComboBox comboBox = new ComboBox
  158.             {
  159.                 Name = qfields[i].Name,
  160.                 SelectionStart = 0,
  161.                 DropDownStyle = ComboBoxStyle.DropDownList,
  162.                 Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
  163.                 Width = base.Width - (qlabel.Location.X + qlabel.Width + SpaceBetweenLabelAndBox)
  164.             };
  165.  
  166.             //список объектов удовлетворяющих типу поля
  167.             List<Cosmetics> SuitableItems = qCosmeticsList.Where(WField => (WField.GetType() == qfields[i].FieldType)).ToList();
  168.  
  169.             //заполнение списка
  170.             for (int j = 0; j < SuitableItems.Count; j++)
  171.             {
  172.                 comboBox.Items.Add(SuitableItems[j].Name);
  173.             }
  174.  
  175.             //Установка связанного обьекта
  176.             var buf = qfields[i].GetValue(qCosmetic);
  177.             int index = -1;
  178.  
  179.             if (buf != null)
  180.             {
  181.                 for (int j = 0; j < SuitableItems.Count; j++)
  182.                 {
  183.                     if (buf.Equals(SuitableItems[j]))
  184.                     {
  185.                         index = j; break;
  186.                     }
  187.                 }
  188.                 comboBox.SelectedIndex = index;
  189.             }
  190.  
  191.             return comboBox;
  192.         }
  193.  
  194.         //сохранение значений полей обьекта
  195.         private void SaveAction(Object sender, EventArgs e)
  196.         {
  197.             if ((pCosmetics == null) || (pCosmeticsList == null))
  198.                 return;
  199.  
  200.             FieldInfo[] fields = pCosmetics.GetType().GetFields();
  201.  
  202.             //Сохранение значений чекбоксов
  203.             foreach (var control in base.Controls.OfType<CheckBox>().ToList())
  204.             {
  205.                 FieldInfo FI = fields.ToList().Where(field => field.Name == control.Name).First();
  206.                 FI.SetValue(pCosmetics, Convert.ChangeType(control.Checked, FI.FieldType));
  207.             }
  208.  
  209.             //Преобразование текста в значение
  210.             foreach (var control in base.Controls.OfType<TextBox>().ToList())
  211.             {
  212.                 if (fields.ToList().Where(field => field.Name == control.Name).Count() != 0)
  213.                 {
  214.                     FieldInfo FI = fields.ToList().Where(field => field.Name == control.Name).First();
  215.                     var FIValue = FI.GetValue(pCosmetics);
  216.                     try
  217.                     {
  218.                         FI.SetValue(pCosmetics, Convert.ChangeType(control.Text, FI.FieldType));
  219.                     }
  220.                     catch
  221.                     {
  222.                         //Восстанавливаем старое значение
  223.                         FI.SetValue(pCosmetics, FIValue);
  224.                         MessageBox.Show(FI.Name + " Error: field text value");
  225.                     }
  226.                 }
  227.             }
  228.  
  229.             //Сохранение значений выпадающих списков
  230.             foreach (var control in base.Controls.OfType<ComboBox>().ToList())
  231.             {
  232.                 if (fields.ToList().Where(field => field.Name == control.Name).Count() != 0)
  233.                 {
  234.                     FieldInfo FI = fields.ToList().Where(field => field.Name == control.Name).First();
  235.                     var FIValye = FI.GetValue(pCosmetics);
  236.  
  237.                     if (control.SelectedIndex == -1)
  238.                         continue;
  239.  
  240.                     if (FI.FieldType.IsEnum)
  241.                     {
  242.                         try
  243.                         {
  244.                             FI.SetValue(pCosmetics, control.SelectedIndex);
  245.                         }
  246.                         catch
  247.                         {
  248.                             FI.SetValue(pCosmetics, FIValye);
  249.                             MessageBox.Show(FI.Name + " Error: field enum value");
  250.                         }
  251.                     }
  252.                     else
  253.                     {
  254.                         List<Cosmetics> SuitableItems = pCosmeticsList.Where(sitem => (sitem.GetType() == FI.FieldType)).ToList();
  255.                         try
  256.                         {
  257.                             FI.SetValue(pCosmetics, SuitableItems[control.SelectedIndex]);
  258.                         }
  259.                         catch
  260.                         {
  261.                             FI.SetValue(pCosmetics, FIValye);
  262.                             MessageBox.Show(FI.Name + " Error: field Enterpriseect value");
  263.                         }
  264.                     }
  265.                 }
  266.             }
  267.         }      
  268.     }
  269. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement