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() where T : class, new() { T val = new(); var propertiesObj = typeof(T).GetProperties(); var columns = dataGridViewTable.Columns.Cast().ToList(); foreach (var property in propertiesObj) { var column = columns.FirstOrDefault(c => c.DataPropertyName == property.Name); if (column != null) { object value = dataGridViewTable.SelectedRows[0].Cells[column.Index].Value; 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 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; } } }