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.Count > 0 ? dataGridView1.SelectedRows[0].Index : -1; 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 && prop.CanWrite) { var value = selectedRow.Cells[column.Index].Value; prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType)); } } return obj; } public void FillData(List students) { dataGridView1.DataSource = null; dataGridView1.Rows.Clear(); foreach (var student in students) { dataGridView1.Rows.Add(student.Group, student.FullName, student.Course); } } } }