我使用OpenFileDialog类打开并显示所选的文件名。
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,都会添加新的文件名,但实际上并非如此!?!
答案 0 :(得分:3)
尝试listBox1.DataSource = null;
,然后将其设置为paths
。
ListBox
很可能没有刷新,因为数据源“没有改变”。 我们知道列表的内容已经改变,但是,从ListBox
的角度来看,对象是相同的。
另一个更好的选择是使用BindingList<string>
, 会在ListBox
更新时随时更新项目,而无需任何额外的小费。
答案 1 :(得分:2)
您必须将文件对话框中的Multiselect
设置为true,然后使用FileNames
属性:
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string[] files = openFileDialog1.FileNames;
paths.AddRange(files);
listBox1.DataSource=paths;
Refresh();
}