using Controls.Exceptions;
using System;
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 Controls
{
public partial class CustomListBox : UserControl
{
///
/// Конструктор по умолчанию
///
public CustomListBox()
{
InitializeComponent();
}
///
/// Строка макет
///
private string _templateString;
///
/// Символ начала
///
private string _startSymbol;
///
/// Символ конца
///
private string _endSymbol;
///
/// Шаблон строки
///
public void SetTemplateString(string templateString, string startSymbol, string endSymbol)
{
if (templateString != "" && startSymbol != "" && endSymbol != "")
{
_templateString = templateString;
_startSymbol = startSymbol;
_endSymbol = endSymbol;
}
else
{
throw new ArgumentNullException("Вы не ввели все значения");
}
}
///
/// Выбранная строка
///
public int SelectedIndex
{
get { return listBoxMain.SelectedIndex; }
set
{
if (listBoxMain.SelectedIndex != 0)
{
listBoxMain.SelectedIndex = value;
}
}
}
///
/// Получение обхекта
///
public T GetObjectFromStr() where T : class, new()
{
if (listBoxMain.SelectedIndex == -1)
{
return null;
}
string row = listBoxMain.SelectedItem.ToString();
T curObject = new T();
StringBuilder sb = new StringBuilder(row);
foreach (var property in typeof(T).GetProperties())
{
if (!property.CanWrite)
{
continue;
}
int borderOne = sb.ToString().IndexOf(_startSymbol);
if (borderOne == -1)
{
break;
}
int borderTwo = sb.ToString().IndexOf(_endSymbol, borderOne + 1);
if (borderTwo == -1)
{
break;
}
string propertyValue = sb.ToString(borderOne + 1, borderTwo - borderOne - 1);
sb.Remove(0, borderTwo + 1);
property.SetValue(curObject, Convert.ChangeType(propertyValue, property.PropertyType));
}
return curObject;
}
///
/// Заполнение
///
public void FillProperty(T dataObject, int rowIndex, string propertyName)
{
while (listBoxMain.Items.Count <= rowIndex)
{
listBoxMain.Items.Add(_templateString);
}
string row = listBoxMain.Items[rowIndex].ToString();
PropertyInfo propertyInfo = dataObject.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
object propertyValue = propertyInfo.GetValue(dataObject);
row = row.Replace($"{_startSymbol}{propertyName}{_endSymbol}", propertyValue.ToString());
listBoxMain.Items[rowIndex] = row;
}
}
}
}