48 lines
1.8 KiB
C#
48 lines
1.8 KiB
C#
using DressAtelierContracts.Attributes;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace SewingDresses
|
|
{
|
|
public static class DataGridViewExtension
|
|
{
|
|
public static void FillAndConfigGrid<T>(this DataGridView grid, List<T>? 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($"In type {type.Name} property with name {column.Name} wasn't found");
|
|
}
|
|
var attribute = property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
|
|
if (attribute == null)
|
|
{
|
|
throw new InvalidOperationException($"Attribute of type ColumnAttribute for property {property.Name} wasn't found");
|
|
}
|
|
// attempt to find proper attribute
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|