109 lines
2.4 KiB
C#
109 lines
2.4 KiB
C#
using System;
|
|
using System.Collections;
|
|
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;
|
|
|
|
namespace KOP_Labs
|
|
{
|
|
public partial class TableComponent : UserControl
|
|
{
|
|
public event EventHandler TaskHandler;
|
|
public int indexRow;
|
|
public int IndexRow
|
|
{
|
|
get
|
|
{
|
|
return indexRow;
|
|
}
|
|
set
|
|
{
|
|
|
|
indexRow = value;
|
|
|
|
}
|
|
}
|
|
public TableComponent()
|
|
{
|
|
InitializeComponent();
|
|
}
|
|
public void TableConfiguration(int columnsQuantity, List<string> headers, List<int> widths, List<bool> isVisual, List<string> names)
|
|
{
|
|
for (int i = 0; i < columnsQuantity; i++)
|
|
|
|
{
|
|
DataGridViewColumn column = new DataGridViewColumn();
|
|
column.Name = names[i];
|
|
column.HeaderText = headers[i];
|
|
column.Width = widths[i];
|
|
column.Visible = isVisual[i];
|
|
column.CellTemplate = new DataGridViewTextBoxCell();
|
|
|
|
dataGridView.Columns.Add(column);
|
|
|
|
}
|
|
}
|
|
public void ClearRows()
|
|
{
|
|
dataGridView.Rows.Clear();
|
|
}
|
|
public void AddRow<T>(T newObject)
|
|
{
|
|
DataGridViewRow row = (DataGridViewRow)dataGridView.Rows[0].Clone();
|
|
|
|
foreach (var prop in newObject.GetType().GetProperties())
|
|
{
|
|
object value = prop.GetValue(newObject);
|
|
|
|
row.Cells[dataGridView.Columns[prop.Name].Index].Value = value;
|
|
}
|
|
|
|
dataGridView.Rows.Add(row);
|
|
}
|
|
|
|
public T GetSelectedObject<T>() where T : new()
|
|
{
|
|
if (dataGridView.SelectedCells.Count == 0)
|
|
{
|
|
return new T();
|
|
}
|
|
|
|
int rowIndex = dataGridView.SelectedCells[0].RowIndex;
|
|
var targetObject = new T();
|
|
Type objectType = typeof(T);
|
|
PropertyInfo[] properties = objectType.GetProperties();
|
|
|
|
foreach (PropertyInfo property in properties)
|
|
{
|
|
DataGridViewCell selectedCell = dataGridView.Rows[rowIndex].Cells[property.Name];
|
|
|
|
object cellValue = selectedCell.Value;
|
|
|
|
if (cellValue != null && property.CanWrite)
|
|
{
|
|
object convertedValue = Convert.ChangeType(cellValue, property.PropertyType);
|
|
property.SetValue(targetObject, convertedValue);
|
|
}
|
|
}
|
|
|
|
return targetObject;
|
|
}
|
|
private void SelectionChanged(object sender, EventArgs e)
|
|
{
|
|
var element = sender as DataGridView;
|
|
if (dataGridView.SelectedRows.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
IndexRow = element.SelectedRows[0].Index;
|
|
TaskHandler?.Invoke(this, e);
|
|
}
|
|
}
|
|
}
|