PIbd-32.-Gerimovich-I.M.-COP/Library15Gerimovich/OutputTableResults.cs
platoff aeeee 7d7ce6cb91 try2
2024-09-17 12:41:48 +04:00

116 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Library15Gerimovich.Models;
namespace Library15Gerimovich
{
public partial class OutputTableResults : UserControl
{
private readonly List<string> _columnsFildsNames = new();
public OutputTableResults()
{
InitializeComponent();
}
public void ConfigureColumns(params CustomDataTableColumnParameter[] columnParameters)
{
dataGridViewOut.Columns.Clear();
_columnsFildsNames.Clear();
for (int i = 0; i < columnParameters.Length; i++)
{
dataGridViewOut.Columns
.Add(columnParameters[i].HeaderName, columnParameters[i].HeaderName);
var column = dataGridViewOut.Columns[i];
column.Visible = columnParameters[i].Visible;
_columnsFildsNames.Add(column.Name);
if (columnParameters[i].Width != 0)
{
column.Width = columnParameters[i].Width;
}
else
{
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
}
}
}
/// <summary>
/// Отчистить таблицу
/// </summary>
public void Clear()
=> dataGridViewOut.Rows.Clear();
/// <summary>
/// Индекс выбранной строки
/// </summary>
public int SelectedRow
{
get => dataGridViewOut.CurrentRow.Index;
set
{
dataGridViewOut.CurrentRow.Selected = false;
dataGridViewOut.Rows[value].Selected = true;
}
}
public TType? GetRow<TType>(int rowIndex)
{
Type type = typeof(TType);
var element = type.GetConstructor([])?.Invoke([]);
if (element is null)
{
return default;
}
var row = dataGridViewOut.Rows[rowIndex].Cells;
for (int i = 0; i < dataGridViewOut.ColumnCount; i++)
{
if (string.IsNullOrEmpty(_columnsFildsNames[i]))
{
continue;
}
var field = type.GetProperty(_columnsFildsNames[i]);
field?.SetValue(element, row[i].Value);
}
return (TType)element;
}
public void Fill<TType>(IList<TType> insertValues)
{
Clear();
Type type = typeof(TType);
for (int i = 0; i < insertValues.Count(); ++i)
{
var row = insertValues[i];
dataGridViewOut.Rows.Add();
for (int j = 0; j < _columnsFildsNames.Count; ++j)
{
dataGridViewOut.Rows[i].Cells[j].Value
= type.GetProperty(_columnsFildsNames[j])?.GetValue(row)!;
}
}
}
}
}