在我的程序中,我有 2 个 ListView 和 1 个按钮。 当我按下按钮时,第一个 ListView 中的每个 ListView 项目都将在第二个 ListView 中被选中。第一个 ListView 中的项目始终存在于第二个 ListView 中,但反之则不然。
我在选择第二个 ListView 中的项目时遇到问题。我正在尝试使用 IndexOf
获取索引。
foreach (ListViewItem item in firstListView.Items)
{
int index = secondListView.Items.IndexOf(item);
secondListView.Items[index].Selected = true;
}
当我点击按钮时,我总是得到一个错误,index
is -1
。而且我不明白我做错了什么。
解决方案
所以我在这里尝试做的是查找属于不同 ListView 的项目的索引,但它并不像那样工作。尽管两个 ListView 中的文本相同,但 ListView 项并不完全相同,因为它们是引用类型。
我无法使用 Text
属性,因为项目可能具有相同的文本。所以我的解决方案是在每个 ListViewItem
的 Tag
属性中放置一个唯一的整数。由于整数是值类型,我可以使用该整数来检查第一个 ListView 中的 ListViewItem
是否在第二个 ListView 中。
// Loop through each item in the first listview
foreach (ListViewItem item1 in firstListView.Items)
{
// For each item in the first listview, loop through the second listview to find if it's there
foreach (ListViewItem item2 in secondListView.Items)
{
// Check if item1 is identical to item2 by looking at its tag
if (int.Parse(item1.Tag) == int.Parse(item2.Tag))
{
// The item has been found and will be selected!
item2.Selected = true;
}
}
}
最佳答案
您可以使用这样的 linq 查询来选择第二个列表中也存在于第一个列表中的项目:
var items = from i1 in listView1.Items.Cast<ListViewItem>()
from i2 in listView2.Items.Cast<ListViewItem>()
where i1.SubItems.Cast<ListViewItem.ListViewSubItem>()
.Where((s, i) => s.Text != i2.SubItems[i].Text).Count() == 0
select i2;
items.ToList().ForEach(x => { x.Selected = true; });
注意:
当尝试使用 secondListView.Items.IndexOf
方法查找属于 firstListView
的项目时,您不能期望它找到该项目。您试图查找其索引的项目不存在于第二个 ListView 的项目集合中。您应该使用项目和子项目的 Text
属性查找项目。
关于c# 如果两个 ListView 包含它,则选择 ListView 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42607936/