95 lines
2.4 KiB
C#
95 lines
2.4 KiB
C#
|
using System.Text;
|
|||
|
|
|||
|
|
|||
|
namespace WinFormsLibrary
|
|||
|
{
|
|||
|
public partial class ListBoxValues : UserControl
|
|||
|
{
|
|||
|
private string _layout;
|
|||
|
private string _endSymbol;
|
|||
|
private string _startSymbol;
|
|||
|
public ListBoxValues()
|
|||
|
{
|
|||
|
InitializeComponent();
|
|||
|
}
|
|||
|
public void SetLayout(string layout, string startSymbol, string endSymbol)
|
|||
|
{
|
|||
|
if (layout == null || startSymbol == null || endSymbol == null)
|
|||
|
{
|
|||
|
return;
|
|||
|
}
|
|||
|
_layout = layout;
|
|||
|
_endSymbol = endSymbol;
|
|||
|
_startSymbol = startSymbol;
|
|||
|
}
|
|||
|
public int SelectedIndex
|
|||
|
{
|
|||
|
get
|
|||
|
{
|
|||
|
if (listBoxObjects.SelectedIndex == -1)
|
|||
|
{
|
|||
|
return -1;
|
|||
|
}
|
|||
|
return listBoxObjects.SelectedIndex;
|
|||
|
}
|
|||
|
set
|
|||
|
{
|
|||
|
if (listBoxObjects.SelectedItems.Count != 0)
|
|||
|
{
|
|||
|
listBoxObjects.SelectedIndex = value;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
public T GetObjectFromStr<T>() where T : class, new()
|
|||
|
{
|
|||
|
string selectedString = "";
|
|||
|
if (listBoxObjects.SelectedIndex != -1)
|
|||
|
{
|
|||
|
selectedString = listBoxObjects.SelectedItem.ToString();
|
|||
|
}
|
|||
|
T curObject = new T();
|
|||
|
foreach (var pr in typeof(T).GetProperties())
|
|||
|
{
|
|||
|
if (!pr.CanWrite)
|
|||
|
{
|
|||
|
continue;
|
|||
|
}
|
|||
|
int borderOne = selectedString.IndexOf(_startSymbol);
|
|||
|
StringBuilder sb = new StringBuilder(selectedString);
|
|||
|
selectedString = sb.ToString();
|
|||
|
int borderTwo = selectedString.IndexOf(_endSymbol);
|
|||
|
if (borderOne == -1 || borderTwo == -1) break;
|
|||
|
string propertyValue = selectedString.Substring(borderOne + 1, borderTwo - borderOne-1);
|
|||
|
selectedString = selectedString.Substring(borderTwo + 1);
|
|||
|
pr.SetValue(curObject, Convert.ChangeType(propertyValue, pr.PropertyType));
|
|||
|
}
|
|||
|
return curObject;
|
|||
|
}
|
|||
|
|
|||
|
public void AddInListBox<T>(List<T> values)
|
|||
|
{
|
|||
|
if (_layout == null || _startSymbol == null || _endSymbol == null)
|
|||
|
{
|
|||
|
MessageBox.Show("заполните информацию о макетной строке");
|
|||
|
return;
|
|||
|
}
|
|||
|
if (!_layout.Contains(_startSymbol) || !_layout.Contains(_endSymbol))
|
|||
|
{
|
|||
|
MessageBox.Show("Макетная строка не содержит нужные элементы");
|
|||
|
return;
|
|||
|
}
|
|||
|
foreach (var item in values)
|
|||
|
{
|
|||
|
string str = _layout;
|
|||
|
foreach (var prop in item.GetType().GetProperties())
|
|||
|
{
|
|||
|
string str1 = $"{_startSymbol}" + $"{prop.Name}" + $"{_endSymbol}";
|
|||
|
str = str.Replace(str1, $"{_startSymbol}" + prop.GetValue(item).ToString() + $"{_endSymbol}");
|
|||
|
}
|
|||
|
listBoxObjects.Items.Add(str);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
}
|