这是C#Windows窗体。
我有一个数据网格视图,该视图应该显示两列,文件名和修改日期。我这样做的方法是通过任务。我也有一个仅包含文件和路径名,bindingsource和数据网格视图的类。此任务运行传递类的方法。任务完成后,该类应具有网格视图,然后可以将其设置回窗体上的gridview。
该类如下所示:
class GetLogFilesParameters
{
public string FileNameandPath;
public BindingSource BindingSource;
public DataGridView GridView;
public GetLogFilesParameters(string _fileNameAndPath)
{
FileNameandPath = _fileNameAndPath;
BindingSource = new BindingSource();
GridView = new DataGridView();
GridView.DataSource = BindingSource;
}
}
我的任务正在调用的方法如下所示:
private static void GetLogFilesTest(GetLogFilesParameters FormFields)
{
Cursor.Current = Cursors.WaitCursor;
try
{
//Setup data table
DataTable FileList = new DataTable();
FileList.Clear();
DataColumn FileNameColumn = new DataColumn();
FileNameColumn.ColumnName = "FileName";
FileNameColumn.DataType = System.Type.GetType("System.String");
DataColumn DateColumn = new DataColumn();
DateColumn.ColumnName = "ModifiedDate";
DateColumn.DataType = System.Type.GetType("System.DateTime");
FileList.Columns.Add(FileNameColumn);
FileList.Columns.Add(DateColumn);
//Get a list of files in a directory
string[] files = Directory.GetFiles(FormFields.FileNameandPath, "*.log");
//Loop through the files and fill the data table with a row for each
foreach (string file in files)
{
FileInfo FileInformation = new FileInfo(file);
DataRow row = FileList.NewRow();
row["FileName"] = FileInformation.Name;
row["ModifiedDate"] = FileInformation.LastWriteTime;
FileList.Rows.Add(row);
}
//FormFields.GridView.Columns.Add("FileName", "File Name");
//FormFields.GridView.Columns.Add("ModifiedDate", "Modified Date");
FormFields.GridView.AutoGenerateColumns = true;
//Setup the binding source
FormFields.BindingSource.DataSource = FileList;
FormFields.BindingSource.Sort = "ModifiedDate DESC";
FormFields.GridView.Columns[0].Width = (FormFields.GridView.Width / 10) * 6;
FormFields.GridView.Columns[1].Width = (FormFields.GridView.Width / 10) * 4;
}
catch (Exception ex)
{
string ErrorText = "Error trying to get the list of log files." + Environment.NewLine + Environment.NewLine;
ExceptionLogger.LogIt(ErrorText, "Exception");
MessageBox.Show(ErrorText + ex.ToString());
}
finally
{
Cursor.Current = Cursors.Default;
}
}
我的任务如下所示:
GetLogFilesParameters GetLogFilesParameters = new GetLogFilesParameters(EpicorSenderPath);
Task tGetFiles1 = new Task(() => GetLogFilesTest(GetLogFilesParameters));
tGetFiles1.Start();
tGetFiles1.ContinueWith((antecedent) =>
{
gvEpicorSenderFiles = GetLogFilesParameters.GridView;
}, TaskScheduler.FromCurrentSynchronizationContext());
我得到的错误是System.ArgumentOutOfRangeException:索引超出范围。必须为非负数并且小于集合的大小。它发生在此行的方法中:
FormFields.GridView.Columns[0].Width = (FormFields.GridView.Width / 10) * 6;
发生这种情况是因为根据调试,gridview没有任何列。另外,当它确实具有行和数据时。我不知道怎么了
最佳答案
我猜(我不明白为什么会这样),您尝试访问尚不存在的列。
尝试在DataGridView.DataBindingComplete事件中移动这些代码行
FormFields.GridView.Columns[0].Width = (FormFields.GridView.Width / 10) * 6;
FormFields.GridView.Columns[1].Width = (FormFields.GridView.Width / 10) * 4;