【发布时间】:2013-07-20 06:41:19
【问题描述】:
我四处寻找,但找不到任何参考资料。
如何删除与listbox 中的项目相关的通用列表中的项目?
我目前有一个public static List<Employees> 和一个名为lstRecords 的listbox,我可以删除listbox 中的项目就好了,但要么从列表中删除所有内容,要么什么都不删除。
这是我使用的第一组代码:
private void DeleteRecord()
{
if (lstRecords.Items.Count > 0)
{
for (int i = 0; i < lstRecords.Items.Count; i++)
{
if (lstRecords.GetSelected(i) == true)
{
Employees employeeRecord = lstRecords.SelectedItem as Employees;
employee.Remove(employeeRecord);
}
}
lstRecords.Items.Remove(lstRecords.SelectedItem);
}
}
}
这是我使用的第二组代码,我的 List 就在部分类下,但这都包含在一个方法中。
private void DeleteRecord()
{
ListBox lstRecords = new ListBox();
List<object> employee = new List<object>();
employee.RemoveAt(lstRecords.SelectedIndex);
lstRecords.Items.RemoveAt(lstRecords.SelectedIndex);
}
到目前为止,我还没有让任何一组代码按照我想要的方式工作,我显然做错了什么。
我还玩过其他一些代码块,但它们似乎朝着正确的方向发展。
最终我需要能够双击列表中的一个项目来拉出属性菜单。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
那么你有什么错误吗?您可以发布您的代码部分以将项目插入列表吗?
-
你的第二个代码对我来说太荒谬了:)。您创建了完全空的
List<>和ListBox并从中删除选定的项目。 :)) 这很有趣。你的实际List<>和ListBox在哪里? -
感谢您帮助编辑我的标题。下次我会努力观察的。
-
您是否尝试单步执行您的代码并查看如何以及何时输入第二个 if 语句?我发现您使用两种选择方法令人困惑:lstRecords.GetSelected() 和 lstRecords.SelectedItem。