c# - 在 C# 中从 ListView 中删除项目

标签 c# listview

我需要从 ListView 中删除项目,我正在寻找的代码将显示一个 MessageBox 以确认,如果没有选择任何项目,它将显示一个错误 MessageBox

这是我的代码,它不起作用:(

private void button2_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems != null)
    {
        var confirmation = MessageBox.Show(
            "Voulez vous vraiment supprimer les stagiaires séléctionnés?",
            "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question
        );

        if (confirmation == DialogResult.Yes)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].Selected)
                {
                    listView1.Items[i].Remove();
                    i--;
                }
            }
        }
    }
    else
    {
        MessageBox.Show("aucin stagiaire selectionnes", "erreur",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

错误不在删除中,而是在 MessageBox 的 中,我有两个 MessageBox 的,在确认之前必须先显示错误。

最佳答案

从末尾开始数到零

for (int i = listView1.Items.Count - 1; i >= 0; i--)
{
    if (listView1.Items[i].Selected)
    {
        listView1.Items[i].Remove();
    }
}

但是考虑到每个 ListViewItem 都有一个 Index 属性,您可以将它与 SelectedItems 集合一起使用,以准备一个具有避免冗余测试和对较少数量项目的循环。

此外,SelectedItems 集合永远不会为空,如果没有选择,则该集合为空但不为空。

所以你的代码可以重写

if (listView1.SelectedItems.Count > 0)
{
    var confirmation = MessageBox.Show("Voulez vous vraiment supprimer les stagiaires séléctionnés?", "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (confirmation == DialogResult.Yes)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            ListViewItem itm = listView1.SelectedItems[i];
            listView1.Items[itm.Index].Remove();
        }
    }
}
else
    MessageBox.Show("aucin stagiaire selectionnes", ...);

关于c# - 在 C# 中从 ListView 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15572169/

相关文章:

android - 按下后退时,Sqlite Listview 会清除

android - 从广播接收器更新 fragment 中的 ListView

c# - 如何使具有相同数据的对象具有相同的键?

c# - 如何取消下载异步?

c# - 将依赖添加为 DLL 或添加为项目

android - ListView 项目在 Android 中不可点击

Fragment 中的 Android 自定义 ArrayAdapter

c# - 锁定 SQLite 数据库以从 C# 读取

c# - 在 Visual Studio 中测试/运行具有受限 CPU/RAM 的 C# 应用程序?

android - Fragment 中的 ListView 未显示在 MainActivity 中