VC++ Windows Application ListView 删除所有选中的项目
VC++ Windows Application ListView delete all selected items
我正在尝试从 listView1 中删除多个 selected 项目,但似乎在删除一个项目后,列表没有得到更新,因此 程序出现故障,即删除了一些错误的项目并跳过了一些正确的项目。
删除一项后,GUI 框会更新,即该项从框中消失。但是第一个之后的下一个不是应该的。
示例: I select 索引为 0、1、3、4 的项目
结果:0被删,然后3被删,然后5被删虽然我没有select5.
注意: 项目select编辑正确(我测试了)。问题出在下面的代码中。
这是我的代码:
private: System::Void delSelected_LinkClicked(System::Object^ sender, System::Windows::Forms::LinkLabelLinkClickedEventArgs^ e)
{
int count = listView1->SelectedItems->Count;
ListView::SelectedIndexCollection^ indexes = this->listView1->SelectedIndices;
System::Collections::IEnumerator^ myEnum1 = indexes->GetEnumerator();
MessageBox::Show(count.ToString(), "MessageBox Test", MessageBoxButtons::OK, MessageBoxIcon::Information);
while (myEnum1->MoveNext()) {
int index = safe_cast<int>(myEnum1->Current);
//MessageBox::Show(index.ToString()+". "+listView1->Items[index]->Text, "MessageBox Test", MessageBoxButtons::OK, MessageBoxIcon::Information);
listView1->Items->Remove(listView1->Items[index]);
}
}
我想知道在删除一个项目后更新列表的方法或任何其他解决方法。
谢谢。
Listview 项目按其索引删除(即它们在列表中的位置,从 0 到 n-1)。
问题是,当删除列表视图项目时,所有后续 项目都向上移动了一个位置。例如,如果您删除项目索引 1,则之前为索引 2 的项目将成为新索引 1,依此类推。
解决方案是:
- 跟踪已删除的项目数,并在删除每个后续项目时从索引中减去总数,或者
- 以相反的顺序删除项目
无论选择哪种解决方案,在开始之前都需要确保要删除的索引列表已排序。
以下是对 Jonathan 回答的直接赞美:
while (listView1->SelectedItems->Count > 0)
{
listView1->Items->Remove(listView1->SelectedItems [0]);
}
这是我在 Jonathan 和 Raheel 的回答的帮助下完成的:
while (listView1->SelectedItems->Count > 0)
listView1->Items->Remove(listView1->SelectedItems[0])
我正在尝试从 listView1 中删除多个 selected 项目,但似乎在删除一个项目后,列表没有得到更新,因此 程序出现故障,即删除了一些错误的项目并跳过了一些正确的项目。
删除一项后,GUI 框会更新,即该项从框中消失。但是第一个之后的下一个不是应该的。
示例: I select 索引为 0、1、3、4 的项目
结果:0被删,然后3被删,然后5被删虽然我没有select5.
注意: 项目select编辑正确(我测试了)。问题出在下面的代码中。
这是我的代码:
private: System::Void delSelected_LinkClicked(System::Object^ sender, System::Windows::Forms::LinkLabelLinkClickedEventArgs^ e)
{
int count = listView1->SelectedItems->Count;
ListView::SelectedIndexCollection^ indexes = this->listView1->SelectedIndices;
System::Collections::IEnumerator^ myEnum1 = indexes->GetEnumerator();
MessageBox::Show(count.ToString(), "MessageBox Test", MessageBoxButtons::OK, MessageBoxIcon::Information);
while (myEnum1->MoveNext()) {
int index = safe_cast<int>(myEnum1->Current);
//MessageBox::Show(index.ToString()+". "+listView1->Items[index]->Text, "MessageBox Test", MessageBoxButtons::OK, MessageBoxIcon::Information);
listView1->Items->Remove(listView1->Items[index]);
}
}
我想知道在删除一个项目后更新列表的方法或任何其他解决方法。
谢谢。
Listview 项目按其索引删除(即它们在列表中的位置,从 0 到 n-1)。
问题是,当删除列表视图项目时,所有后续 项目都向上移动了一个位置。例如,如果您删除项目索引 1,则之前为索引 2 的项目将成为新索引 1,依此类推。
解决方案是:
- 跟踪已删除的项目数,并在删除每个后续项目时从索引中减去总数,或者
- 以相反的顺序删除项目
无论选择哪种解决方案,在开始之前都需要确保要删除的索引列表已排序。
以下是对 Jonathan 回答的直接赞美:
while (listView1->SelectedItems->Count > 0)
{
listView1->Items->Remove(listView1->SelectedItems [0]);
}
这是我在 Jonathan 和 Raheel 的回答的帮助下完成的:
while (listView1->SelectedItems->Count > 0)
listView1->Items->Remove(listView1->SelectedItems[0])