如何从列表框中删除选定的项目C# [英] How to Remove selected item from listbox C#

查看:21
本文介绍了如何从列表框中删除选定的项目C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试查看用户在列表框中选择的所有文件和文件夹.目前,我可以使用 openfiledialogue 列出用户选择的内容,但是当我尝试从列表框中删除它时,我现在面临问题.我试图让用户单击文件旁边的复选框,然后按删除按钮将其删除

i currently trying to view all the files and folder selected by the user in a listbox. At the Moment i am able to list what the user have chosen using the openfiledialogue HOWEVER i am now facing prob when i try to remove it form the listbox. i trying to allow the user to click on the checkbox beside the file and press the remove button to remove it

这是我删除按钮的代码

      private void button2_Click(object sender, EventArgs e)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            listView1.Items.Remove(listView1.SelectedItems[i]);
        }

    }

这是添加到列表框的文件以供参考,以防万一

this is the add file to listbox for reference jsut in case

    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog openfiledialog = new OpenFileDialog();
        // Display open file dialog
        openfiledialog.InitialDirectory = "C:\";
        //openfiledialog.Multiselect = true;
        openfiledialog.Title = "Lock File";
        openfiledialog.Filter = "All Files | *.*";
        openfiledialog.ShowDialog();


        if (openfiledialog.FileName != "")
        {

        //move through FileInfo array and store in new array of fi
            listView1.Items.Clear();
            foreach (string file in openfiledialog.FileNames)
            {
                listView1.Items.Add(file);
            }        
        }

    }

我按下删除按钮没有任何反应,我在谷歌上看到了一些关于使用 selectionmode 的答案,但是当我使用它时,我的列表框没有 selectionmode 的属性,并且有红线下划线

and i pressed the remove button nothing happen and i saw some answer on google on the using of selectionmode but when i used that, my listbox does not have the property of selectionmode and have red lines underlined

推荐答案

不要使用 listView1.SelectedItems 而是使用 listView1.CheckedItems 并更改您的 button2_click到:

Instead of using listView1.SelectedItems use listView1.CheckedItems and change your button2_click to:

private void button2_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem i in listView1.CheckedItems)
                listView1.Items.Remove(i);

        }

这篇关于如何从列表框中删除选定的项目C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆