[英]Winforms Listbox databinding to list of files in a directory
我想将目录中的文件列表绑定到列表框。
这是到目前为止我想要的代码片段,lstFiles是一个ListBox,我想将Files属性绑定到。 但是列表框为空。 请帮忙。
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
}
我看不到将文件添加到您的代码列表中,
DirectoryInfo dinfo = new DirectoryInfo(@"C:\Directory");
文件类型
_files = dinfo.GetFiles("*.txt");
然后
foreach( FileInfo file in Files )
{
listbox1.Items.Add(file.Name);
}
您必须设置valuemember属性。 我尝试例如:
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;
这按预期工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.