PIbd-31_Malafeev.L.S._COP_25/Cop_25/Controls/CustomListBox.cs

133 lines
3.8 KiB
C#

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
{
/// <summary>
/// Конструктор по умолчанию
/// </summary>
public CustomListBox()
{
InitializeComponent();
}
/// <summary>
/// Макет
/// </summary>
private string _templateString;
/// <summary>
/// Символ начала
/// </summary>
private string _startSymbol;
/// <summary>
/// Символ конца
/// </summary>
private string _endSymbol;
/// <summary>
/// Шаблон строки
/// </summary>
public void SetTemplateString(string templateString, string startSymbol, string endSymbol)
{
if (templateString != "" && startSymbol != "" && endSymbol != "")
{
_templateString = templateString;
_startSymbol = startSymbol;
_endSymbol = endSymbol;
}
else
{
throw new ArgumentNullException("Вы не ввели все значения");
}
}
/// <summary>
/// Выбранная строка
/// </summary>
public int SelectedIndex
{
get { return listBoxMain.SelectedIndex; }
set
{
if (listBoxMain.SelectedIndex != 0)
{
listBoxMain.SelectedIndex = value;
}
}
}
/// <summary>
/// Получение обхекта
/// </summary>
public T GetObjectFromStr<T>() 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;
}
/// <summary>
/// Заполнение
/// </summary>
public void FillProperty<T>(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;
}
}
}
}