C# 删除标记对象

问题描述 投票:0回答:2

我有关于使用“标签”的问题:

我有一个ListBox或ListView,其中有我的对象的名称,我添加了一个“Tag”属性来查找其相应的对象:

foreach(Operation op_ass in ListOpAss1)
{
    op_ass.getNom(Properties.Settings.Default.Langue);
    ListViewItem item = new ListViewItem(op_ass.Nom);
    item.Tag = op_ass;
    listBoxAss1.Items.Add(op_ass.Nom);
}

现在我想要的是,当我选择列表中的一个(或多个)项目时,对相应的对象执行操作。但我怎样才能把它们找回来呢? 例如,我想从列表中删除选定的对象,或者获取操作 ID 的列表(不在我的列表中显示 ID)。

c# winforms tags
2个回答
3
投票

看起来您正在将属性

op_ass.Nom
添加到列表框中,而不是 ListViewItem
item
。修改您的代码如下:

foreach (Operation op_ass in ListOpAss1)
   {
       op_ass.getNom(Properties.Settings.Default.Langue);
       ListViewItem item = new ListViewItem(op_ass.Nom);
       item.Tag = op_ass;

       // Add the list view item instead of op_ass.Nom
       listBoxAss1.Items.Add(item);
   }

现在您应该能够从所选项目中检索标签,如下所示:

var operation = ((listBox1.SelectedItem as ListViewItem).Tag) as Operation;

或者,您可以考虑使用数据绑定,如下所示:

 foreach (Operation op_ass in ListOpAss1)
   {
      op_ass.getNom(Properties.Settings.Default.Langue);
   }

 listBoxAss1.DataSource = ListOpAss1;
 listBoxAss1.DisplayMember = "Nom";

并按如下方式访问数据绑定对象:

var operation = listBox1.SelectedItem as Operation;

-1
投票

使用 foreach 已被弃用,您可以在对象列表中查看已实现的函数

ListOpAss1.ForEach(x=> 
{
    x.getNom(Properties.Settings.Default.Langue);
    var item = new ListViewItem(x.Nom);
    item.Tag = x;
    listBoxAss1.Items.Add(x.Nom);
});

为了选择列表中的项目,您可以对多个文件使用 SingleOrDefalt() 或 Skip(count) take (count),或者您可以运行带条件的本机查询来搜索列表,如下所示

var items = collection.Where(x=> x.City == "Burgas").ToList(); //You can use select if you want only certain properties of the object to be selected
///then you can use that new item list to remove the objects from the collection list like this
items.ForEach(x=> 
{
    collection.Remove(x);
});
© www.soinside.com 2019 - 2024. All rights reserved.