чет проверила в лабе, подправила (в третьем компоненте...)

вроде работает
This commit is contained in:
Елена Бакальская 2024-09-23 01:06:36 +04:00
parent bbc5701cbc
commit da7b64ec6f
4 changed files with 41 additions and 18 deletions

View File

@ -56,6 +56,7 @@
listComponent.SelectedIndex = -1;
listComponent.Size = new Size(406, 315);
listComponent.TabIndex = 2;
listComponent.ChangeSelectedItem += ChangeSelectedItem;
//
// FormTest
//

View File

@ -43,6 +43,7 @@ namespace TestAppForCheckComponentsWorking
public class Cat()
{
public string? Name { get; set; }
public int? Age { get; set; }
}
public void FillListBox()
@ -51,9 +52,10 @@ namespace TestAppForCheckComponentsWorking
{
Cat cat = new Cat();
cat.Name = i.ToString();
cat.Age = i;
try
{
listComponent.FillTemplateString("Êîò ñ è ìåíåì (Name)", "(", ")");
listComponent.FillTemplateString("Êîò ñ èìåíåì (Name)", "(", ")");
}
catch (Exception ex)
{
@ -62,6 +64,15 @@ namespace TestAppForCheckComponentsWorking
listComponent.AddObjectToListBox(cat);
}
}
private void ChangeSelectedItem(object sender, EventArgs e)
{
listComponent.GetObjectFromSelectedRow<Cat>();
string placeHolder = "(Name)";
listComponent.ExtractValueFromTemplate("Êîò ñ èìåíåì (Name)", placeHolder);
}
}
}

View File

@ -39,6 +39,7 @@
listBox.Name = "listBox";
listBox.Size = new Size(319, 244);
listBox.TabIndex = 0;
listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
//
// ListComponent
//

View File

@ -17,9 +17,12 @@ namespace UserComponentsOption19
private string? _startPropertyChar;
private string? _endPropertyChar;
public event EventHandler? ChangeSelectedItem;
public ListComponent()
{
InitializeComponent();
//listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
}
/// <summary>
@ -66,12 +69,14 @@ namespace UserComponentsOption19
}
}
public T? GetObjectFromSelectedRow<T>() where T : new()
public T? GetObjectFromSelectedRow<T>() where T : class, new()
{
if (listBox.SelectedItem == null)
return default;
if (listBox.SelectedIndex == -1 || listBox.SelectedItem == null)
return null;
string? selectedString = listBox.SelectedItem.ToString();
//MessageBox.Show(selectedString);
T obj = new T();
// Получаем тип объекта
@ -85,38 +90,41 @@ namespace UserComponentsOption19
{
// Извлекаем значение свойства из строки
string value = ExtractValueFromTemplate(selectedString, placeholder);
MessageBox.Show(value.ToString());
// Преобразуем значение в нужный тип
object convertedValue = Convert.ChangeType(value, property.PropertyType);
MessageBox.Show(convertedValue.ToString());
// Устанавливаем значение свойства через рефлексию
property.SetValue(obj, convertedValue);
}
}
return obj;
}
// Метод для извлечения значения между плейсхолдерами
private string ExtractValueFromTemplate(string templateString, string placeholder)
{
int startIndex = templateString.IndexOf(placeholder) + placeholder.Length;
int endIndex = templateString.IndexOf(_endPropertyChar, startIndex);
// имя кота: (Барсик)
if (endIndex == -1) endIndex = templateString.Length;
// Метод для извлечения значения между плейсхолдерами
public string ExtractValueFromTemplate(string templateString, string placeholder)
{
int startIndex = templateString.IndexOf(placeholder) + 1;
int endIndex = templateString.IndexOf(_endPropertyChar);
if (endIndex < 0) endIndex = templateString.Length; // ЛУЧШЕ СДЕЛАТЬ ИСКЛЮЧЕНИЕ
MessageBox.Show(templateString.Substring(startIndex, endIndex - startIndex).Trim());
return templateString.Substring(startIndex, endIndex - startIndex).Trim();
}
// Параметризованный метод для добавления объекта в ListBox
// Параметризованный метод для добавления объекта в листбокс
public void AddObjectToListBox<T>(T? obj)
{
// Получаем тип объекта
Type objectType = obj.GetType();
// Создаем строку на основе макетной строки
string resultString = _templateString;
// Проходим по всем свойствам объекта
foreach (var propertyInfo in objectType.GetProperties())
{
string placeholder = $"{_startPropertyChar}{propertyInfo.Name}{_endPropertyChar}";
@ -125,10 +133,12 @@ namespace UserComponentsOption19
// Заменяем плейсхолдеры значениями из объекта
resultString = resultString.Replace(placeholder, value);
}
// Добавляем полученную строку в ListBox
listBox.Items.Add(resultString);
listBox.Items.Add(resultString);
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
ChangeSelectedItem?.Invoke(this, e);
}
}
}