2017-03-09 59 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