在这段代码中,我正在检查文件夹根目录中的所有文件,并仅将相关文件添加到我的Listbox中。我想要一个选项,每次迭代都会标记我的列表框中的最后一项。
我认为它应该使用此命令:listBoxFiles.SetSelected(listBoxFiles.Items.Count, true);
但是如果我在每次将项目添加到我的列表框 ArgumentOutOfRange 错误后将其放入。
private void btnAddDir_Click_1(object sender, EventArgs e)
{
int totalCount = 0;
int count = 0;
string fileToAdd = string.Empty;
List<string> filesList = new List<string>();
BackgroundWorker backgroundWorker = null;
DialogResult dialog = folderBrowserDialog1.ShowDialog();
if (dialog == DialogResult.OK)
{
btnAddfiles.Enabled = false;
btnAddDir.Enabled = false;
btnPlay.Enabled = false;
Editcap editcap = new Editcap();
foreach (string file in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
{
if (editcap.isWiresharkFormat(file))
{
filesList.Add(file);
totalCount++;
}
}
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s1, e1) =>
{
foreach (string fileName in filesList)
{
if (editcap.isWiresharkFormat(fileName))
{
if (editcap.isLibpcapFormat(fileName))
{
backgroundWorker.ReportProgress(0, fileName);
count++;
}
else if (!editcap.isLibpcapFormat(fileName))
{
fileToAdd = editcap.getNewFileName(fileName);
backgroundWorker.ReportProgress(0, fileToAdd);
count++;
}
this.Invoke((MethodInvoker)delegate
{
labelStatus.Text = string.Format("Please wait..({0}/{1} files added)", count, totalCount);
});
}
}
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s1, e1) =>
{
});
backgroundWorker.ProgressChanged +=
(s1, arguments) =>
{
listBoxFiles.Items.Add(arguments.UserState);
};
backgroundWorker.RunWorkerAsync();
}
}
答案 0 :(得分:3)
listBoxFiles.SetSelected(listBoxFiles.Items.Count - 1, true);