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 ListBoxMany : UserControl { public ListBoxMany() { 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 listBox.SelectedIndex; } set { if (listBox.SelectedIndex != 0) { listBox.SelectedIndex = value; } } } public T GetObjectFromStr() 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; } public void FillProperty(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; } } } }