【发布时间】:2017-03-23 20:36:49
【问题描述】:
我有一个保存的列表框。当有人退出程序时,它会将所有名称保存在列表框中,当他们进入时,会将它们全部添加回来。
问题是,当表单打开并且 listBox2 为空时,它很好并且可以执行它的功能。但是当程序在 Form_Load 上自动将文本框中的项目加载到 listBox2 时,单击 listBox2 时出现以下错误。
“System.ArgumentOutOfRangeException”类型的未处理异常 发生在 mscorlib.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);
}
}
}
【问题讨论】:
-
将 Form_Load 中的代码添加到问题中。
-
我添加了 Form_Load 代码