将值从清单框保存到文本文件,然后打开文本文件并将保存的值重新填充回表单中
本文关键字:文本 文件 保存 新填充 填充 表单 单框 然后 | 更新日期: 2023-09-27 18:34:04
我正在尝试将所选项目从类型保存到文本文件(复选框框)。
我也将主要演员(树视图)保存到文本文件中
这部分有效,他们正在保存。
但是,当我尝试打开文本文件以将数据重新填充回表单时,
出现错误:
索引超出数组的范围。
以下是保存和打开函数的代码:
private void openDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
// Open the file and upload the information
openFileDialog1.ShowDialog();
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
saveDatabaseToolStripMenuItem.Enabled = true;
string infomovie = reader.ReadLine();
string[] select = infomovie.Split('#');
int nline = select.Length;
txtTitle.Text = select[0];
txtYear.Text = select[1];
txtDir.Text = select[2];
txtDur.Text = select[3];
int nactors = Convert.ToInt32(select[4]);
// put the number of actors in the file
for (int i = 0; i < nactors; i++)
{
tvActor.Nodes.Add(select[4 + i]);
}//end of for loop
int genre = Convert.ToInt32(select[5]);
// put the number of actors in the file
for (int i = 0; i < genre; i++)
{
cBoxType.Items.Add(select[5 + i]);
}//end of for loop
reader.Close();
}
private void saveDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
{
//save data enter into form to text file
saveFileDialog1.ShowDialog();
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
//creates string called infomovie
String infomovie = "";
//prints parameters
infomovie += txtTitle.Text + "#";
infomovie += txtYear.Text + "#";
infomovie += txtDir.Text + "#";
infomovie += txtDur.Text + "#";
//gets values from check list box
int genre = cBoxType.Items.Count;
infomovie += genre.ToString() + "#";
//gets values for tree view
int nactors = tvActor.Nodes.Count;
infomovie += nactors.ToString() + "#";
for (int i = 0; i < nactors; i++)
{
//convert treeview to string
infomovie += tvActor.Nodes[i].Text + ",";
}
//sep
infomovie += "#";
for (int i = 0; i < genre; i++)
{
if (cBoxType.GetItemCheckState(i) == CheckState.Checked)
{
//if statement to check which boxes are selected then converts to string
infomovie += cBoxType.Items[i].ToString() + ",";
}
}
//sep
infomovie += "#";
writer.WriteLine(infomovie);
writer.Close();
}
你的actor count stored at index 5
,genre count is at 4
和Actorlist at 6
,用,
分隔,所以你必须在索引 6 处获取元素,然后按,
拆分它们,并循环它并将其添加到tvActor.Nodes
string[] actorlist= select[6].Split(',');
// Then Do loop here
流派列表也是如此。