using System.Text; namespace CustomComponents { public partial class ListBoxObjects : UserControl { private string layoutString; private string startSymbol; private string endSymbol; public ListBoxObjects() { InitializeComponent(); } public void SetLayoutInfo(string layout, string startS, string endS) { if (layout == null || startS == null || endS == null) { return; } layoutString = layout; startSymbol = startS; endSymbol = endS; } public int SelectedIndex { get { if (listBox.SelectedIndex == -1) { return -1; } return listBox.SelectedIndex; } set { if (listBox.SelectedItems.Count != 0) { listBox.SelectedIndex = value; } } } public T GetObjectFromStr() where T : class, new() { string selStr = ""; if (listBox.SelectedIndex != -1) { selStr = listBox.SelectedItem.ToString()!; } T curObject = new T(); foreach (var property in typeof(T).GetProperties()) { if (!property.CanWrite) { continue; } int borderOne = selStr.IndexOf(startSymbol); StringBuilder sb = new StringBuilder(selStr); sb[borderOne] = 'z'; selStr = sb.ToString(); int borderTwo = selStr.IndexOf(endSymbol); if (borderOne == -1 || borderTwo == -1) break; string propertyValue = selStr.Substring(borderOne + 1, borderTwo - borderOne - 1); selStr = selStr.Substring(borderTwo + 1); property.SetValue(curObject, Convert.ChangeType(propertyValue,property.PropertyType)); } return curObject; } public void AddInListBox(T entity) { if (layoutString == null || startSymbol == null || endSymbol == null) { throw new Exception("Заполните макетную строку"); } if (!layoutString.Contains(startSymbol) || !layoutString.Contains(endSymbol)) { throw new Exception("Макетная строка не содержит нужные элементы"); } string str = layoutString; foreach (var prop in entity.GetType().GetProperties()) { string str1 = $"{startSymbol}" + $"{prop.Name}" + $"{endSymbol}"; str = str.Replace(str1, $"{startSymbol}" + prop.GetValue(entity).ToString() + $"{endSymbol}"); } listBox.Items.Add(str); } } }