[英]Winforms Listbox databinding to list of files in a directory
I want to bind a list of files in a directory to a list box. 我想将目录中的文件列表绑定到列表框。
Here is a code snippet of want i tried so far, lstFiles is a ListBox, I want to bind the Files property to. 这是到目前为止我想要的代码片段,lstFiles是一个ListBox,我想将Files属性绑定到。 But the ListBox is empty. 但是列表框为空。 Please help. 请帮忙。
public partial class Form1 : Form, INotifyPropertyChanged
{
private IList<FileInfo> _files = new List<FileInfo>();
public IList<FileInfo> Files
{
get
{
return this._files;
}
set
{
if (value != this._files)
{
this._files = value;
NotifyPropertyChanged("Files");
}
}
}
public Form1()
{
InitializeComponent();
lstFiles.DataSource = Files;
lstFiles.DataBindings.Add("Name", Files, "Files");
lstFiles.DisplayMember = "Name";
}
private void btnStartPath_Click(object sender, EventArgs e)
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
txtStartPath.Text = dialog.SelectedPath;
}
}
private void btnFind_Click(object sender, EventArgs e)
{
Files = new DirectoryInfo(txtStartPath.Text).EnumerateFiles().ToList();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
I don't see adding files to list in your code, 我看不到将文件添加到您的代码列表中,
DirectoryInfo dinfo = new DirectoryInfo(@"C:\Directory");
Files type, 文件类型
_files = dinfo.GetFiles("*.txt");
then 然后
foreach( FileInfo file in Files )
{
listbox1.Items.Add(file.Name);
}
You have to set the valuemember property. 您必须设置valuemember属性。 I tried this for example: 我尝试例如:
IList<FileInfo> myList = new List<FileInfo>();
FileInfo test1 = new FileInfo(@"G:\test.xls");
myList.Add(test1);
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "FullName";
listBox1.DataSource = myList;
This works as expected :) 这按预期工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.