2017-03-09 58 views
1

我有一个列表框,其数据源是包含文件夹名称的列表。我想从列表框和路径中删除文件夹,但第一个不起作用。使用DataSource从列表框中删除项目

下面的代码:

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); 

    } 
+0

使用调试器告诉你为什么。在'String folder = lb.SelectedItem.ToString();'行放置一个停止点并遵循发生的情况。 – LarsTech

+0

文件夹取自lb.selecteditem的值 “文件夹” lb.datasource有17个文件夹s 之前我把value设为null lb.selecteditem现在是“”; themesF有17个文件夹,与数据源完全一样。 随着我删除,我有16个文件夹, lb.Datasource = themesF它有16个文件夹。 所选项目现在是folder1但仍为选定文件夹 – Seeker

+0

使用BindingList而不是List。在click事件中删除这些DataSource行。 – LarsTech

回答

0

List<T>不报告更改列表,那么请尝试使用BindingList<T>代替:

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

从Remove_Click活动中删除那些数据源行,因为那些没有必要了。只需设置一次数据源。

0

试试这个:

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); 

} 

当你想删除列表中的东西,一种方法是先找到它。 而当你写这个:lb.DataSource =东西;你不需要先在那里放置null。

+0

用此,该文件夹被删除,但仍然显示在列表框中。 – Seeker

+0

如果lb.SelectedItem.Text中的文本是你的字符串的文本,它将被删除。或者你可以这样写:themesF.Remove(themesF.Find(t => t.Equals(lb.SelectedItem.Text))); 。都是一样的 –

+0

它是,但我不知道为什么这种形式它不适合我。无论如何,非常感谢评论。 – Seeker