using FormLibrary.HelperClasses; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormLibrary { public partial class ValueTableControl : UserControl { public ValueTableControl() { InitializeComponent(); ConfigureDataGridView(); } private void ConfigureDataGridView() { dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.MultiSelect = false; dataGridView1.RowHeadersVisible = false; dataGridView1.AllowUserToAddRows = false; dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } public void ConfigureColumns(List<(string HeaderText, string DataPropertyName, float FillWeight)> columns) { dataGridView1.Columns.Clear(); foreach (var column in columns) { dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = column.HeaderText, DataPropertyName = column.DataPropertyName, FillWeight = column.FillWeight }); } } public void ClearRows() { dataGridView1.Rows.Clear(); } public int SelectedRowIndex { get => dataGridView1.SelectedRows[0].Index; set { if (value >= 0 && value < dataGridView1.Rows.Count) { dataGridView1.ClearSelection(); dataGridView1.Rows[value].Selected = true; } } } public T GetSelectedObject() where T : new() { if (dataGridView1.SelectedRows.Count == 0) throw new InvalidOperationException("Нет выбранной строки."); var selectedRow = dataGridView1.SelectedRows[0]; var obj = new T(); foreach (DataGridViewColumn column in dataGridView1.Columns) { var prop = typeof(T).GetProperty(column.DataPropertyName); if (prop != null) { var value = selectedRow.Cells[column.Index].Value; prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType)); } } return obj; } public void FillData(List objects) { dataGridView1.Rows.Clear(); if (objects == null || !objects.Any()) { return; } var properties = typeof(T).GetProperties(); foreach (var obj in objects) { var values = properties.Select(p => p.GetValue(obj, null)).ToArray(); dataGridView1.Rows.Add(values); } } } }