100 lines
3.4 KiB
C#
Raw Normal View History

2024-09-09 22:02:46 +04:00
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 CreateVisualComponent
{
public partial class ListOutputComponent : UserControl
{
public ListOutputComponent()
{
InitializeComponent();
}
public int SelectedRow
{
get { return dataGridViewTable.SelectedRows[0].Index; }
set
{
if (dataGridViewTable.SelectedRows.Count <= value || value < 0)
throw new ArgumentException(string.Format("{0} is an invalid row index.", value));
else
{
dataGridViewTable.ClearSelection();
dataGridViewTable.Rows[value].Selected = true;
}
}
}
public void ClearDataGrid()
{
dataGridViewTable.DataSource = null;
dataGridViewTable.Rows.Clear();
}
public void ConfigColumn(ColumnsConfiguratoin columnsData)
{
dataGridViewTable.ColumnCount = columnsData.ColumnsCount;
for (int i = 0; i < columnsData.ColumnsCount; i++)
{
dataGridViewTable.Columns[i].Name = columnsData.ColumnName[i];
dataGridViewTable.Columns[i].Width = columnsData.Width[i];
dataGridViewTable.Columns[i].Visible = columnsData.Visible[i];
dataGridViewTable.Columns[i].DataPropertyName = columnsData.PropertiesObject[i];
}
}
public T GetSelectedObjectInRow<T>() where T : class, new()
{
T val = new();
var propertiesObj = typeof(T).GetProperties();
2024-09-14 18:15:23 +04:00
var columns = dataGridViewTable.Columns.Cast<DataGridViewColumn>().ToList();
2024-09-09 22:02:46 +04:00
foreach (var property in propertiesObj)
{
2024-09-14 18:15:23 +04:00
var column = columns.FirstOrDefault(c => c.DataPropertyName == property.Name);
if (column != null)
2024-09-09 22:02:46 +04:00
{
2024-09-14 18:15:23 +04:00
object value = dataGridViewTable.SelectedRows[0].Cells[column.Index].Value;
2024-09-09 22:02:46 +04:00
Type propertyType = property.PropertyType;
bool isNullable = Nullable.GetUnderlyingType(propertyType) != null;
if (isNullable)
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
if (value != DBNull.Value)
{
property.SetValue(val, Convert.ChangeType(value, propertyType));
}
else if (isNullable)
{
property.SetValue(val, null);
}
}
}
return val;
}
public void AddItem<T>(T item, int RowIndex, int ColumnIndex)
{
if (item == null)
return;
string propertyName = dataGridViewTable.Columns[ColumnIndex].DataPropertyName.ToString();
string? value = item.GetType().GetProperty(propertyName)?.GetValue(item)?.ToString();
if (RowIndex >= dataGridViewTable.Rows.Count)
{
dataGridViewTable.RowCount = RowIndex + 1;
}
dataGridViewTable.Rows[RowIndex].Cells[ColumnIndex].Value = value;
}
}
}