2016-02-22 127 views
0
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 

namespace POC1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

      string[] files = Directory.GetFiles(@"C:\\"); 
      foreach (string file in files) 
      { 
       comboBox1.Items.AddRange(files); 
      } 
     } 

    } 
} 

我使用下面的代碼,但我無法讓我的組合框填充任何數據。我很確定我使用了我搜索過的例子。用目錄文件填充組合框

+2

你能用'comboBox1.DataSource = files; comboBox1.DataBind();'? FBD似乎也未被使用。 – ibiza

+0

使用斷點,'文件'在調用GetFiles之後是否有任何條目?此外for循環看起來有問題。 '文件中的文件'...'AddRange(fileS)' – KDecker

+0

@ibiza我現在刪除它。我的錯。 – Intelwalk

回答

1

不,它可能會有所作爲,但你的循環,並通過添加所有目錄中的時間有目錄的數量。應該更像

string[] files = Directory.GetFiles(@"C:\\"); 
     foreach (string file in files) 
     { 
      comboBox1.Items.Add(file); 
     } 

或簡單

comboBox1.Items.AddRange(Directory.GetFiles(@"C:\\")); 

而且,除非你有別的地方(是自香港專業教育學院使用的WinForms一段時間),你需要設置你的窗體加載事件。

this.Load += Form1_Load; 
+1

如果他雙擊表單以使其自動生成,他不需要註冊它,它已經完成。但是,如果他只是複製並粘貼這個,那麼是的。那就是問題所在。 – DiscipleMichael

0

您或者需要刪除循環,並有一個.AddRange(文件),或者將循環內部的行更改爲comboBox.Items.Add(file),如上例所示,爲每次迭代添加所有文件。

值得注意的是,添加項目時,它不一定是一個字符串,但可以是一個對象,它只需要適當地響應.ToString()。

看到這個鏈接,https://social.msdn.microsoft.com/Forums/windows/en-US/c7a82a6a-763e-424b-84e0-496caa9cfb4d/how-add-a-item-to-combobox?forum=winforms

+0

你是對的,它絕對是爲每個文件添加整個文件夾的內容,但這並不能解決他的問題顯示在所有。 – DiscipleMichael