c# - 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;
}
解决方案
推荐阅读
- android - 即使视图是最后一个元素,如何将 recyclerview 视图放在顶部?
- javascript - 无法使用 CSSTransition Group 创建平滑滚动
- angular - 使用 ngIf 表达式根据选择选项值有条件地显示元素
- javascript - 我需要比较 JavaScript 中的两个值,并根据这些值将状态设置为可用
- c - 如何在printf中填充两个字符串?
- intellij-idea - 范围报告 - 使用 Intellij IDEA 打开 html 页面时不显示图像
- javascript - 如何在 php 中使用 wordpress 函数 wp_enqueue_script()?
- google-maps - Flutter GoogleMap load alertdialog 在华为 P10+ 上随机加载失败
- tensorflow - aws sagemaker python sdk:预测函数给出奇怪的错误
- python - 如何从 Django 调用 REST API?