// Заполняем comboBoxQuality элементами
comboBoxQuality.Items.AddRange(new string[] { "Обычное", "Редкое", "Легендарное" });
comboBoxQuality.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxQuality.Visible = false;
comboBoxQuality.SelectedIndexChanged += ComboBoxSelectedIndexChanged;
// Добавляем ComboBox на форму
listView1.Controls.Add(comboBoxEnchantment);
listView1.Controls.Add(comboBoxQuality);
}
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
ListViewHitTestInfo hit = listView1.HitTest(e.Location);
ListViewItem.ListViewSubItem subItem = hit.SubItem;
if (hit.Item != null && subItem != null)
{
int subItemIndex = hit.Item.SubItems.IndexOf(subItem);
if (subItemIndex == 5) // Индекс колонки зачарования
{
ShowComboBox(comboBoxEnchantment, subItem);
}
else if (subItemIndex == 6) // Индекс колонки качества
{
ShowComboBox(comboBoxQuality, subItem);
}
// Создаем новый прямоугольник с учетом смещения
Rectangle rect = new Rectangle(hit.SubItem.Bounds.Left, hit.SubItem.Bounds.Top + 22,
hit.SubItem.Bounds.Width, hit.SubItem.Bounds.Height);
// Настраиваем textBox
textBoxEditor.Bounds = rect;
textBoxEditor.Text = hit.SubItem.Text;
textBoxEditor.Visible = true;
textBoxEditor.BringToFront();
textBoxEditor.Focus();
textBoxEditor.SelectAll();
}
}
private void ApplyTextToSelectedItem()
{
var selectedItems = listView1.SelectedItems;
if (selectedItems.Count > 0 && textBoxEditor.Visible)
{
ListViewItem item = selectedItems[0];
// Проверяем, что новое значение является числом
if (int.TryParse(textBoxEditor.Text, out int value))
{
// В полученный индекс подставляем индекс колонки "Количество"
item.SubItems[2].Text = value.ToString();
}
else
{
MessageBox.Show("Введите числовое значение.");
}
textBoxEditor.Visible = false;
}
}
private void ShowComboBox(ComboBox comboBox, ListViewItem.ListViewSubItem subItem)
{
// Вычисляем и устанавливаем позицию и размер ComboBox
comboBox.Bounds = subItem.Bounds;
comboBox.SelectedItem = subItem.Text; // Устанавливаем выбранный элемент соответствующий текущему тексту
comboBox.Visible = true;
comboBox.BringToFront();
comboBox.Focus();
}
private void ComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
ComboBox comboBox = sender as ComboBox;
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
int subItemIndex = (comboBox == comboBoxEnchantment) ? 5 : 6;
item.SubItems[subItemIndex].Text = comboBox.SelectedItem.ToString();
comboBox.Visible = false;
}
}
private void LoadImages(string folderPath)
{
Items.PopulateListView(listView2, imageList1);
listView1.ListViewItemSorter = new SortList(1);
listView2.ListViewItemSorter = new SortList(1);
DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
if (!dirInfo.Exists)
{
MessageBox.Show($"Директория с изображениями не найдена: { folderPath}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
foreach (FileInfo file in dirInfo.GetFiles("*.png"))
{
try
{
string key = Path.GetFileNameWithoutExtension(file.Name);
Image image = Image.FromFile(file.FullName);
imageList1.Images.Add(key, image);
}
catch (Exception ex)
{
MessageBox.Show("Ошибкка" +ex);
}
}
}
private void TransferSelectedItems()
{
if (listView2.SelectedItems.Count > 0)
{
foreach (ListViewItem selectedItem in listView2.SelectedItems)
{
ListViewItem newItem = (ListViewItem)selectedItem.Clone();
// Очистим предыдущие подэлементы, чтобы добавить их заново в правильном порядке
newItem.SubItems.Clear();
// Сначала добавляем ключ изображения как первичный подэлемент
newItem.ImageKey = selectedItem.ImageKey;
// Затем добавляем все остальные подэлементы в правильном порядке
newItem.SubItems.Add(selectedItem.SubItems[1].Text); // Название предмета
// Поскольку количество всегда по умолчанию 1 при добавлении,
// его можно добавить сразу после названия
newItem.SubItems.Add("1"); // Количество
// Указываем остальные подэлементы с учётом того,
// что первый остаётся на месте и является названием
newItem.SubItems.Add(selectedItem.SubItems[2].Text); // Категория
newItem.SubItems.Add(selectedItem.SubItems[3].Text); // Уровень
// Для зачарования и качества ставим пустые строки,
// так как эти значения определить заранее невозможно
newItem.SubItems.Add(""); // Зачарование
newItem.SubItems.Add(""); // Качество
AddedItems.Add(selectedItem.ImageKey); // Добавляем в список добавленных элементов
addedItemsList.Add(newItem); // Добавляем в список для правильного отображения при фильтрации
listView2.Items.Remove(selectedItem); // Удаляем из второго списка
}
UpdateListView1(textBoxSearchListView1.Text); // Обновляем первый список
listView1.Refresh(); // Обновляем отображение первого списка
}
}
private void addItem_Click(object sender, EventArgs e)
{
TransferSelectedItems();
}
private void removeItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
foreach (ListViewItem selectedItem in listView1.SelectedItems)
{
ListViewItem newItem = new ListViewItem();
newItem.ImageKey = selectedItem.ImageKey;
AddedItems.Remove(selectedItem.ImageKey);
newItem.SubItems.Add(selectedItem.SubItems[1].Text);
newItem.SubItems.Add(selectedItem.SubItems[3].Text);
newItem.SubItems.Add(selectedItem.SubItems[4].Text);
listView2.Items.Add(newItem);
var itemToRemove = addedItemsList.FirstOrDefault(i => i.ImageKey == selectedItem.ImageKey);
if (itemToRemove != null)
{
addedItemsList.Remove(itemToRemove);
}
listView1.Items.Remove(selectedItem);
}
}
}
private void UpdateListView1(string searchText)
{
var filteredItems = new List<ListViewItem>();
if (string.IsNullOrWhiteSpace(searchText))
{
filteredItems.AddRange(addedItemsList);
}
else
{
foreach (ListViewItem lvi in addedItemsList)
{
string itemName = lvi.SubItems[1].Text;
if (itemName.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
{
filteredItems.Add(lvi);
}
}
}
listView1.BeginUpdate();
listView1.Items.Clear();
listView1.Items.AddRange(filteredItems.ToArray());
listView1.EndUpdate();
}
private void UpdateListView2(string searchText)
{
listView2.Items.Clear();
foreach (var item in Items.ItemsList)
{
if (!AddedItems.Contains(item.ImagePath) &&
(item.Name.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0 ||
item.RuName.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0))
{
ListViewItem lvi = new ListViewItem();
lvi.ImageKey = item.ImagePath;
lvi.SubItems.Add(item.GetNameByCulture(CultureInfo.CurrentUICulture));
lvi.SubItems.Add(item.Category);
lvi.SubItems.Add(item.Level.ToString());
listView2.Items.Add(lvi);
}
}
listView2.Refresh();
}
private void textBoxSearchListView1_TextChanged(object sender, EventArgs e)
{
UpdateListView1(textBoxSearchListView1.Text);
}
private void textBoxSearchListView2_TextChanged(object sender, EventArgs e)
{
UpdateListView2(textBoxSearchListView2.Text);
}
}