简体   繁体   English

使用DataSource从ListBox中删除项目

[英]Delete Item from ListBox with DataSource

I have a listbox whose DataSource is a List who contains folders name. 我有一个列表框,其DataSource是一个包含文件夹名称的列表。 I want delete the folders from listbox and the path, but the first it doesn't work. 我想从列表框和路径中删除文件夹,但第一个它不起作用。

Here the code: 这里的代码:

private static List<string> themesF;

 public Form1()
        {
            InitializeComponent();

 List<string> dirs = new List<string (System.IO.Directory.GetDirectories(@"Thems"));
var pngs = System.IO.Directory.GetFiles(@"Thems").Where(s => s.EndsWith(".png"));
            themesF = new List<string>();

            for (int i = 0; i < dirs.Count; i++)
            {
                themesF.Add(dirs[i].Substring(6));
                Console.WriteLine("A) Directorio " + dirs[i]);
                Console.WriteLine("B) Carpeta" + themesF[i]);
            }
            lb.DataSource = themesF;
            pbx.ImageLocation = (@"Thems\" + themesF[0] + @"\Preview.png");

        }
private void btnRemove_Click(object sender, EventArgs e)
    {
        String folder = lb.SelectedItem.ToString();
        themesF.Remove(folder);
        lb.DataSource = null;
        lb.DataSource = themesF;
        System.IO.Directory.Delete(@"Thems\" + folder,true);

    }

Try this : 尝试这个 :

private void btnRemove_Click(object sender, EventArgs e)
{
    string folder = themesF.Find(t=> t.Equals(lb.SelectedItem.Text));
    themesF.Remove(folder);
    lb.DataSource = themesF;
    System.IO.Directory.Delete(@"Thems\" + folder,true);

}

When you want to delete something from list, one way is find it first. 如果要从列表中删除某些内容,可以先找到一种方法。 And when you write this : lb.DataSource = something; 当你写这个:lb.DataSource = something; You don't need to put null there first. 您不需要先将null放在那里。

List<T> doesn't report changes to the list, so try using a BindingList<T> instead: List<T>不报告对列表的更改,因此请尝试使用BindingList<T>

BindingList<string> themesF = new BindingList<string>();

Remove those DataSource lines from the Remove_Click event since those won't be necessary anymore. 从Remove_Click事件中删除这些DataSource行,因为不再需要这些行。 Just set the DataSource once. 只需设置一次DataSource即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM