首页 > 解决方案 > Winforms - listbox 从列表中的选中项中获取对象

问题描述

我是 Winforms 的新手,需要一些帮助。

我正在尝试从项目列表中获取所选对象并在单击按钮时使用它。

问题接缝是我不知道以正确的方式获取 selectedItem 对象。

谁能帮我解决这个问题?

// fist I will add the object to a list like this:
petList.Add(new Dog(animalName));

// Then I will retrieve the last item and add it to the listbox:
var addedPet = petList.Last();
AnimalList.Items.Add($"{addedPet.GetType().Name} {addedPet.AnimalName} Lycka: {addedPet.Happiness} Trötthet: {addedPet.Tierdness} Hunger: {addedPet.Hungriness} ");

// When I have a selected item I would like to be able to click a button and execute 
private void PlayButton_Click(object sender, EventArgs e)
{
    string resultText = "Inget djur valt från listan, vänligen välj ett djur.";

    // I believe the error occurs here:  
    // When I step in the code I can see that "pet" is NULL but I have the string that was added to the list.
    Animal pet = AnimalList.SelectedItem as Animal;

    if (pet != null) 
    {
        resultText = pet.Play();
        MessageBox.Show($"Du har nu lekt med {pet.AnimalName}");
    }

    TextBoxOutPut.Text = resultText;
}

标签: c#winformslistbox

解决方案


推荐阅读