Files
PIbd-31_Egorov_M.A._COP_34/Components/Components/CustomListBox.cs
2025-08-29 15:03:38 +04:00

128 lines
3.6 KiB
C#

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 Components
{
public partial class CustomListBox : UserControl
{
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 listBox.SelectedIndex; }
set
{
if (listBox.SelectedIndex != 0)
{
listBox.SelectedIndex = value;
}
}
}
/// <summary>
/// Получение обхекта
/// </summary>
public T GetObjectFromStr<T>() where T : class, new()
{
if (listBox.SelectedIndex == -1)
{
return null;
}
string row = listBox.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 (listBox.Items.Count <= rowIndex)
{
listBox.Items.Add(_templateString);
}
string row = listBox.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());
listBox.Items[rowIndex] = row;
}
}
}
}