我有一个保存的列表框。当有人退出程序时,它将保存列表框中的所有名称,当他们进入时,它将重新添加所有名称。
问题是,当表单打开并且 listBox2 为空时,它很好并且可以执行其功能。但是当程序在Form_Load上自动将文本框中的项目加载到 listBox2 中时,当我单击 listBox2 时出现以下错误。
类型为"System.ArgumentOutOfRangeException"的未处理异常 发生在姆科利布.dll
其他信息:索引超出范围。必须为非负数 并且小于集合的大小。
在字符串fullFileName = selectedFiles[listBox2.SelectedIndex];
private void materialFlatButton3_Click_1(object sender, EventArgs e)
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
fullFileName = new List<String>(OpenFileDialog1.FileNames);
foreach (string s in OpenFileDialog1.FileNames)
{
listBox2.Items.Add(Path.GetFileName(s));
selectedFiles.Add(s);
}
}
}
List<string> selectedFiles = new List<string>();
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex >= 0)
{
string fullFileName = selectedFiles[listBox2.SelectedIndex];
textBox4.Text = fullFileName;
}
else
{
}
string path = @"C:Save.txt";
private void Form1_Load(object sender, EventArgs e)
{
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
else
{
StreamReader sr = new StreamReader(path);
string line = string.Empty;
try
{
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
this.listBox2.Items.Add(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
//close the file
sr.Close();
}
textBox3.Visible = false;
string text = File.ReadAllText(path, Encoding.UTF8);
}
}
}
您的代码存在很大缺陷,您有一个带有文件名的ListBox
,以及一个带有路径的List<string>
,但您只将数据保存在ListBox
上,因此当您恢复ListBox
的内容时,您的List<string>
仍然为空,这就是为什么它会在SelectedIndexChanged
上给您一个例外。
您还需要以某种方式存储路径,然后在加载时恢复它。最简单的解决方案可以是交错文件上的数据,保存列表框中的文件名,列表中的路径等,直到保存所有内容,然后当您读回它时,您为列表框恢复一行名称,为列表恢复一行带有路径的列表。
编辑:更好的是,与其保存ListBox
的内容,不如保存List<string>
的内容,然后您可以执行以下操作:
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
this.listBox2.Items.Add(Path.GetFileName(line));
selectedFiles.Add(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();