PIbd-32_Safiulova_K.N._COP/COP_7/ListBoxMany.cs

102 lines
3.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
2024-09-16 21:57:13 +04:00
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
2024-09-16 21:57:13 +04:00
namespace Components
{
public partial class ListBoxMany : UserControl
{
public ListBoxMany()
{
InitializeComponent();
}
2024-09-16 21:57:13 +04:00
private string _templateString;
private string _startSymbol;
private string _endSymbol;
public void SetTemplateString(string templateString, string startSymbol, string endSymbol)
{
2024-09-16 21:57:13 +04:00
if (templateString != "" && startSymbol != "" && endSymbol != "")
{
2024-09-16 21:57:13 +04:00
_templateString = templateString;
_startSymbol = startSymbol;
_endSymbol = endSymbol;
}
else
{
throw new ArgumentNullException("Введены не все значения");
}
2024-09-16 21:57:13 +04:00
}
public int SelectedIndex
{
get { return listBox.SelectedIndex; }
set
{
2024-09-16 21:57:13 +04:00
if (listBox.SelectedIndex != 0)
{
listBox.SelectedIndex = value;
}
}
}
2024-09-16 21:57:13 +04:00
public T GetObjectFromStr<T>() where T : class, new()
{
2024-09-16 21:57:13 +04:00
if (listBox.SelectedIndex == -1)
{
2024-09-16 21:57:13 +04:00
return null;
}
2024-09-16 21:57:13 +04:00
string row = listBox.SelectedItem.ToString();
T curObject = new T();
StringBuilder sb = new StringBuilder(row);
foreach (var property in typeof(T).GetProperties())
{
2024-09-16 21:57:13 +04:00
if (!property.CanWrite)
{
continue;
}
int borderOne = sb.ToString().IndexOf(_startSymbol);
if (borderOne == -1)
{
2024-09-16 21:57:13 +04:00
break;
}
2024-09-16 21:57:13 +04:00
int borderTwo = sb.ToString().IndexOf(_endSymbol, borderOne + 1);
if (borderTwo == -1)
{
break;
}
2024-09-16 21:57:13 +04:00
string propertyValue = sb.ToString(borderOne + 1, borderTwo - borderOne - 1);
sb.Remove(0, borderTwo + 1);
property.SetValue(curObject, Convert.ChangeType(propertyValue, property.PropertyType));
}
2024-09-16 21:57:13 +04:00
return curObject;
}
2024-09-16 21:57:13 +04:00
public void FillProperty<T>(T dataObject, int rowIndex, string propertyName)
{
2024-09-16 21:57:13 +04:00
while (listBox.Items.Count <= rowIndex)
{
2024-09-16 21:57:13 +04:00
listBox.Items.Add(_templateString);
}
2024-09-16 21:57:13 +04:00
string row = listBox.Items[rowIndex].ToString();
PropertyInfo propertyInfo = dataObject.GetType().GetProperty(propertyName);
2024-09-16 21:57:13 +04:00
if (propertyInfo != null)
{
2024-09-16 21:57:13 +04:00
object propertyValue = propertyInfo.GetValue(dataObject);
row = row.Replace($"{_startSymbol}{propertyName}{_endSymbol}", propertyValue.ToString());
listBox.Items[rowIndex] = row;
}
}
}
2024-09-16 21:57:13 +04:00
}