我有一个代表要“处理”的 XML 文件的类。我已经创建了这些对象的 BindingList 并将其绑定到 DataGridView 以便用户(即我)可以稍微“控制”一些东西并“看到”正在发生的事情。默认情况下,构造函数假定列表中的所有文件都将被“处理”:
public class InputFileInfo : INotifyPropertyChanged
{
private bool processThisFile;
public bool Process
{
get { return processThisFile; }
set
{
processThisFile = value;
this.NotifyPropertyChanged("Process");
}
}
public string FileName { get; set; }
public int Rows { get; set; }
public string Message { get; set; }
// constructor
public InputFileInfo(string fName)
{
Process = true;
FileName = fName;
Rows = 0;
Message = String.Empty;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
DGV 中名为“Process”的第一列可能未选中,在这种情况下,我想跳过该文件(即行)并继续下一个。DGV 的最后 2 列旨在显示从已处理的 XML 文件发出的输出行数以及放置某种消息(例如“OK”或“错误文本”)的位置。
简而言之,我希望 DataGridView 成为流程的可视化表示,在 2 个小列中回显结果,并允许用户通过取消选中它来跳过一行。
单击按钮开始处理 DGV 中的文件。到目前为止,这是我所描绘的(似乎有效,但 DGV 并未反映在 fileInfo.Rows 和 fileInfo.Message 中所做的更改):
----- 编辑更新:根据 David Hall 的建议,通过 BindingList (_filesToParse) 循环是解决此问题的好方法(工作代码如下):
private void btnProcess_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("output-file.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
OutputColumnNamesAsFirstLine(writer);
foreach (InputFileInfo fileInfo in _filesToParse)
{
if (fileInfo.Process == true)
{
try
{
fileInfo.Rows = processFile(writer, fileInfo.FileName);
}
catch (Exception ex)
{
log.Warn("Error processing DataGridView:\r\n", ex);
}
}
else
{
fileInfo.Rows = 0;
fileInfo.Message = "skipped";
}
}
writer.Dispose();
fs.Dispose();
MessageBox.Show("All selected files have been processed.");
}
最好的方法是什么?
- 循环遍历 BindingList ?
- 循环通过 DataGridView ?
我认为我需要的是“双向”绑定,但我可能不需要?我接近了吗?
-----------------编辑(更新)----------------
是的,XML 文件已经存在。以下是该部分的工作原理:
private void initializeFileList(string rootFolder) // populate grid with .xml filenames to be processed
{
String root = rootFolder;
var result = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories)
.Select(name => new InputFileInfo(name))
.ToList();
_filesToParse = new BindingList<InputFileInfo>(result.ToList());
dataGridView1.DataSource = _filesToParse;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
btnProcess.Visible = true;