0
我已经有保存部分了,我知道它的工作原理,但是当我点击加载按钮时,它不会显示任何我已经从文本框中保存的文本框.txt文件从txt加载到C#列表框中的
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Grades : Form
{
private StreamWriter fil;
public Grades()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
fil = new StreamWriter("saying.txt"); //This is the txt file
}
catch (DirectoryNotFoundException exc)
{
lstBxDisplay.Text = "Nothing " +
exc.Message;
}
catch (System.IO.IOException exc)
{
lstBxDisplay.Text = exc.Message;
}
}
// saving the files to the saying.txt
private void btnSaveAs_Click(object sender, EventArgs e)
{
try
{
fil.WriteLine(txtBxLastName.Text);
txtBxLastName.Text = "";
txtBxLastName.Focus();
}
catch (System.IO.IOException exc)
{
lstBxDisplay.Text = exc.Message;
}
}
// next is the load button to load the files into the list/display box
private void btnLoad_Click(object sender, EventArgs e)
{
string inValue;
try
{
using (StreamReader infil =
new StreamReader("saying.txt"))
{
inValue = infil.ReadLine();
while (inValue != null)
{
inValue = infil.ReadLine();
if (inValue != null)
this.lstBxDisplay.Items.Add(inValue);
} // end of while
} // end of using
}
catch (System.IO.IOException exc)
{
lstBxDisplay.Text = exc.Message;
}
}
private void Grades_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
fil.Close();
}
catch
{
}
}
}
}
为什么不加载到列表框中的任何原因?我已经尝试过标签和文本框来显示消息,但他们都没有工作。我调试了程序,它执行得很好
我得到了fil.Close();部分在您重新发布代码的第二部分之前,感谢您的建议。但是,我尝试了一个txtBxFirstName,并且它显示的是txtBxLastName。尝试过fil.Close后txtBxFirstName和之前和两者 – Joe
请参阅第2部分,因为它只显示'txtBxLastName'。您的原始代码正在读取(获取第一行),然后检查null,然后输入您的循环。此时,在将第一行添加到列表框之前,您需要进行第二次阅读。所以,你基本上跳过你的第一次阅读。看看在循环中,我如何切换'lstBxDisplay.Items.Add(inValue)'和'inValue = infil.ReadLine()'的位置。 – Mikanikal