2024-11-27 23:43:53 +04:00

105 lines
3.2 KiB
C#

using System.Data;
namespace WinFormsLibrary1
{
public partial class TableComponent : UserControl
{
public TableComponent()
{
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<T>() where T : new()
{
if (dataGridView1.SelectedRows.Count == 0)
throw new Error("Нет выбранной строки.");
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<T>(List<T> objects)
{
dataGridView1.Rows.Clear();
if (objects == null || !objects.Any())
{
return;
}
var columns = dataGridView1.Columns;
foreach (var obj in objects)
{
List<Object> list = new List<Object>();
var properties = typeof(T).GetProperties();
for (int i = 0; i < columns.Count; i++)
{
var v = from p in properties where p.Name == columns[i].DataPropertyName select p;
list.Add(v.First().GetValue(obj,null));
// break;
}
dataGridView1.Rows.Add(list.ToArray());
}
}
private void TableComponent_Load(object sender, EventArgs e)
{
}
}
}