Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Windows.Forms;
- using System.Reflection;
- namespace OOP_UI
- {
- public partial class ItemForm : Form
- {
- private Cosmetics pCosmetics;
- private List<Cosmetics> pCosmeticsList;
- const int formWidth = 500;
- const int formMinHeight = 60;
- const int fieldHeight = 25;
- const int paddingLeft = 15;
- const int paddingUp = 25;
- const int SpaceBetweenLabelAndBox = 30;
- public ItemForm(Cosmetics Cosmetic, List<Cosmetics> CosmeticsList)
- {
- //список всех полей объекта
- FieldInfo[] fields = Cosmetic.GetType().GetFields();
- //получение имени формы
- string fieldName = Cosmetic.GetType().ToString();
- //если у экземляра класса имеется атрибут с названием, то форма будет иметь соответствующее имя
- object[] attributes = Cosmetic.GetType().GetCustomAttributes(typeof(InfoAttribute), inherit: true);
- if (attributes.Length != 0)
- {
- InfoAttribute myAttr = (InfoAttribute)attributes[0];
- fieldName = myAttr.Name;
- }
- //создание пустой формы для редактирования полей
- base.Text = fieldName;
- base.Size = new System.Drawing.Size(formWidth, formMinHeight + fieldHeight * (fields.Length + 2));
- base.MaximizeBox = false;
- //создание полей
- for (int i = 0; i < fields.Length; i++)
- {
- //получение имени для Label
- fieldName = fields[i].GetType().ToString();
- //если у поля имеется атрибут с названием, то форма будет иметь соответствующее имя
- attributes = fields[i].GetCustomAttributes(typeof(InfoAttribute), true);
- if (attributes.Length != 0)
- {
- InfoAttribute myAttr = (InfoAttribute)attributes[0];
- fieldName = myAttr.Name;
- }
- //надпись содержащая тип и имя поля
- Label label = new Label
- {
- Location = new Point(paddingLeft, paddingUp * (i + 1)),
- Width = base.Width / 2,
- Text = fieldName
- };
- base.Controls.Add(label);
- //1 можно использовать рефакторинг
- //Создание для стандартных типов значений текстовых полей ввода, и их заполнение
- if (fields[i].FieldType == typeof(bool))
- {
- base.Controls.Add(MakeCheckBox(fields, Cosmetic, label, i));
- }
- else if (((fields[i].FieldType.IsPrimitive) && (!fields[i].FieldType.IsEnum))
- || (fields[i].FieldType == typeof(string)))
- {
- base.Controls.Add(MakeTextBox(fields, Cosmetic, label, i));
- }
- //Создание выпадающих списков для перечислимых типов
- else if (fields[i].FieldType.IsEnum)
- {
- base.Controls.Add(MakeEnumBox(fields, Cosmetic, label, i));
- }
- //Создание выпадающих списков для вложенных членов
- else if ((!fields[i].FieldType.IsPrimitive) && (!fields[i].FieldType.IsEnum) && (!(fields[i].FieldType == typeof(string))))
- {
- base.Controls.Add(MakeObjectBox(fields, Cosmetic, CosmeticsList, label, i));
- }
- //1
- }
- //кнопка сохранения
- Button SaveBut = new Button
- {
- Name = "SaveBut",
- Text = "Save",
- Location = new Point(base.Width / 2 - (base.Width / 8), (fields.Length + 1) * (fieldHeight + 1)),
- Width = base.Width / 4,
- DialogResult = DialogResult.OK,
- };
- pCosmetics = Cosmetic;
- pCosmeticsList = CosmeticsList;
- SaveBut.Click += SaveAction;
- base.Controls.Add(SaveBut);
- }
- private CheckBox MakeCheckBox(FieldInfo[] qfields, Cosmetics qCosmetic, Label qlabel, int i)
- {
- CheckBox check = new CheckBox()
- {
- Name = qfields[i].Name,
- Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
- Checked = (bool)qfields[i].GetValue(qCosmetic)
- };
- return check;
- }
- private TextBox MakeTextBox(FieldInfo[] qfields, Cosmetics qCosmetic, Label qlabel, int i)
- {
- TextBox textBox = new TextBox
- {
- Name = qfields[i].Name,
- Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
- Width = base.Width - (qlabel.Location.X + qlabel.Width + SpaceBetweenLabelAndBox),
- Text = qfields[i].GetValue(qCosmetic).ToString()
- };
- return textBox;
- }
- private ComboBox MakeEnumBox(FieldInfo[] qfields, Cosmetics qCosmetic, Label qlabel, int i)
- {
- ComboBox comboBox = new ComboBox
- {
- Name = qfields[i].Name,
- SelectionStart = 0,
- DropDownStyle = ComboBoxStyle.DropDownList,
- Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
- Width = base.Width - (qlabel.Location.X + qlabel.Width + SpaceBetweenLabelAndBox)
- };
- comboBox.Items.AddRange(qfields[i].FieldType.GetEnumNames());
- comboBox.SelectedIndex = (int)(qfields[i].GetValue(qCosmetic));
- return comboBox;
- }
- private ComboBox MakeObjectBox(FieldInfo[] qfields, Cosmetics qCosmetic, List<Cosmetics> qCosmeticsList, Label qlabel, int i)
- {
- ComboBox comboBox = new ComboBox
- {
- Name = qfields[i].Name,
- SelectionStart = 0,
- DropDownStyle = ComboBoxStyle.DropDownList,
- Location = new Point(paddingLeft + qlabel.Width, fieldHeight * (i + 1)),
- Width = base.Width - (qlabel.Location.X + qlabel.Width + SpaceBetweenLabelAndBox)
- };
- //список объектов удовлетворяющих типу поля
- List<Cosmetics> SuitableItems = qCosmeticsList.Where(WField => (WField.GetType() == qfields[i].FieldType)).ToList();
- //заполнение списка
- for (int j = 0; j < SuitableItems.Count; j++)
- {
- comboBox.Items.Add(SuitableItems[j].Name);
- }
- //Установка связанного обьекта
- var buf = qfields[i].GetValue(qCosmetic);
- int index = -1;
- if (buf != null)
- {
- for (int j = 0; j < SuitableItems.Count; j++)
- {
- if (buf.Equals(SuitableItems[j]))
- {
- index = j; break;
- }
- }
- comboBox.SelectedIndex = index;
- }
- return comboBox;
- }
- //сохранение значений полей обьекта
- private void SaveAction(Object sender, EventArgs e)
- {
- if ((pCosmetics == null) || (pCosmeticsList == null))
- return;
- FieldInfo[] fields = pCosmetics.GetType().GetFields();
- //Сохранение значений чекбоксов
- foreach (var control in base.Controls.OfType<CheckBox>().ToList())
- {
- FieldInfo FI = fields.ToList().Where(field => field.Name == control.Name).First();
- FI.SetValue(pCosmetics, Convert.ChangeType(control.Checked, FI.FieldType));
- }
- //Преобразование текста в значение
- foreach (var control in base.Controls.OfType<TextBox>().ToList())
- {
- if (fields.ToList().Where(field => field.Name == control.Name).Count() != 0)
- {
- FieldInfo FI = fields.ToList().Where(field => field.Name == control.Name).First();
- var FIValue = FI.GetValue(pCosmetics);
- try
- {
- FI.SetValue(pCosmetics, Convert.ChangeType(control.Text, FI.FieldType));
- }
- catch
- {
- //Восстанавливаем старое значение
- FI.SetValue(pCosmetics, FIValue);
- MessageBox.Show(FI.Name + " Error: field text value");
- }
- }
- }
- //Сохранение значений выпадающих списков
- foreach (var control in base.Controls.OfType<ComboBox>().ToList())
- {
- if (fields.ToList().Where(field => field.Name == control.Name).Count() != 0)
- {
- FieldInfo FI = fields.ToList().Where(field => field.Name == control.Name).First();
- var FIValye = FI.GetValue(pCosmetics);
- if (control.SelectedIndex == -1)
- continue;
- if (FI.FieldType.IsEnum)
- {
- try
- {
- FI.SetValue(pCosmetics, control.SelectedIndex);
- }
- catch
- {
- FI.SetValue(pCosmetics, FIValye);
- MessageBox.Show(FI.Name + " Error: field enum value");
- }
- }
- else
- {
- List<Cosmetics> SuitableItems = pCosmeticsList.Where(sitem => (sitem.GetType() == FI.FieldType)).ToList();
- try
- {
- FI.SetValue(pCosmetics, SuitableItems[control.SelectedIndex]);
- }
- catch
- {
- FI.SetValue(pCosmetics, FIValye);
- MessageBox.Show(FI.Name + " Error: field Enterpriseect value");
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement