2011-06-05 68 views
2

我使用OpenFileDialog類來打開並顯示所選的文件名。ListBox Winform問題

 List<string> paths; 
    private void openFileDialog1_FileOk(object sender, CancelEventArgs e) 
    { 
     label1.Text = "Now you can save the file paths or remove them from the list above"; 
     paths.Add(openFileDialog1.FileName); 
     listBox1.DataSource=paths ;//Only one file is displayed in the listbox 
     Refresh(); 

    } 

我想讓用戶選擇幾個文件並顯示他在我有的列表框中選擇的所有文件。問題是每次只顯示一個文件路徑。有趣的是,當我使用pahts.Add時,我添加了新的文件名,但實際上並不是這樣的!?!

回答

2

你必須設置Multiselect在文件對話框爲true,然後使用FileNames屬性:

private void openFileDialog1_FileOk(object sender, CancelEventArgs e) 
{ 
    string[] files = openFileDialog1.FileNames; 
    paths.AddRange(files); 
    listBox1.DataSource=paths; 
    Refresh(); 
} 
+0

+1 - 一個更好的選擇多文件 - 如果用戶想要從不同的位置選擇多個文件,則需要將其與在OP。 – 2011-06-05 17:22:47

+0

中建立列表的方法結合起來,但它仍然不能工作,它只添加一個文件:( – WithFlyingColors 2011-06-05 17:39:39

3

嘗試listBox1.DataSource = null;然後將其設置爲paths

最有可能的ListBox不刷新,因爲數據源'沒有改變'。 我們知道列表的內容已經改變了,但從ListBox的角度來看,對象是一樣的。

另一種更好的選擇是在每當沒有任何額外的小提琴演奏中添加項目ListBox更新使用BindingList<string>應該結果。

+0

文件[我++] = openFileDialog1.FileName; listBox1.DataSource = files; //我只是做了這個,並沒有工作。與一個字符串它的作品..與字符串列表它沒有:( – WithFlyingColors 2011-06-05 17:50:25

+0

你有沒有嘗試過設置'listBox1.DataSource = null;'之前設置它等於'文件'? – 2011-06-05 17:52:43