platoff aeeee 4def6e88ff done
2024-10-01 10:20:10 +04:00

95 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
public OutputTableResults()
{
InitializeComponent();
}
// установка и получение индекса выбранной строки
public int SelectedRow
{
get => dataGridViewOut.SelectedRows.Count == 1 ? dataGridViewOut.SelectedRows[0].Index : -1;
set
{
if (value >= 0)
{
dataGridViewOut.Rows[value].Selected = true;
}
}
}
// Конфигурация столбцов.
// Для каждого столбца указываются заголовок, ширина, видимость и имя свойства/поля объекта
public void ConfigureColumns(List<ColumnInfo> Columns)
{
dataGridViewOut.ColumnCount = Columns.Count;
for (int Index = 0; Index < Columns.Count; ++Index)
{
dataGridViewOut.Columns[Index].HeaderText = Columns[Index].Header;
dataGridViewOut.Columns[Index].Width = Columns[Index].Width;
dataGridViewOut.Columns[Index].Visible = Columns[Index].IsVisible;
dataGridViewOut.Columns[Index].Name = Columns[Index].Name;
}
}
// очистка строк
public void ClearGrid()
{
dataGridViewOut.Rows.Clear();
}
// получение объекта из выбранной строки
public T GetSelectedObject<T>() where T : new()
{
T RetVal = new T();
var Properties = typeof(T).GetProperties();
var Cells = dataGridViewOut.SelectedRows[0].Cells;
for (int Index = 0; Index < dataGridViewOut.ColumnCount; ++Index)
{
DataGridViewColumn Column = dataGridViewOut.Columns[Index];
var Cell = Cells[Index];
var Property = Properties.FirstOrDefault(x => x.Name == Column.Name);
Property?.SetValue(RetVal, Cell.Value);
}
return RetVal;
}
// заполнение таблицы через передаваемый объект класса T
public void InsertValue<T>(T Object)
{
var Type = typeof(T);
var Properties = Type.GetProperties();
int NewRowIndex = dataGridViewOut.Rows.Add();
foreach (DataGridViewColumn Column in dataGridViewOut.Columns)
{
var Property = Properties.FirstOrDefault(x => x.Name == Column.Name);
if (Property == null)
throw new InvalidOperationException($"В типе {Type.Name} не найдено свойство с именем {Column.Name}");
var Value = Property.GetValue(Object);
dataGridViewOut.Rows[NewRowIndex].Cells[Column.Index].Value = Value;
}
}
}
}