From da635e477a71f4c2e32b98c1d50341e41740c0c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9B=D0=B5=D0=BE=D0=BD=D0=B8=D0=B4=20=D0=9C=D0=B0=D0=BB?= =?UTF-8?q?=D0=B0=D1=84=D0=B5=D0=B5=D0=B2?= Date: Sat, 18 May 2024 13:22:46 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BD=D0=B0=D0=B4=D0=BE=20=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D0=B9=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../JewerlyStoreView/DataGridViewExtension.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 JewelryStore/JewerlyStoreView/DataGridViewExtension.cs diff --git a/JewelryStore/JewerlyStoreView/DataGridViewExtension.cs b/JewelryStore/JewerlyStoreView/DataGridViewExtension.cs new file mode 100644 index 0000000..ee6ca15 --- /dev/null +++ b/JewelryStore/JewerlyStoreView/DataGridViewExtension.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using JewelryStoreContracts.Attributes; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace JewerlyStoreView +{ + public static class DataGridViewExtension + { + public static void FillAndConfigGrid(this DataGridView grid, List? data) + { + if (data == null) + { + return; + } + grid.DataSource = data; + + var type = typeof(T); + var properties = type.GetProperties(); + foreach (DataGridViewColumn column in grid.Columns) + { + var property = properties.FirstOrDefault(x => x.Name == column.Name); + if (property == null) + { + throw new InvalidOperationException($"В типе {type.Name} не найдено свойство с именем {column.Name}"); + } + var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault(); + if (attribute == null) + { + throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {property.Name}"); + } + + if (attribute is ColumnAttribute columnAttr) + { + column.HeaderText = columnAttr.Title; + column.Visible = columnAttr.Visible; + if (columnAttr.IsUseAutoSize) + { + column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), columnAttr.GridViewAutoSize.ToString()); + } + else + { + column.Width = columnAttr.Width; + } + } + } + } + } +}