所以,我是C#的新手,我的程序中有这个列表框,它复制了它从文本框中读取的内容。 每当我启动程序时,它会将save.txt文件的内容加载到列表框中,但是当它执行此操作时,它会加载所有save.txt内容的副本。我在加载内容之前尝试清除列表框但它没有工作。
这是我的代码:
private void readList()
{
string line;
listBox.Items.Clear(); //I tried to clear the listbox but it's not working
listBox.Items.AddRange(File.ReadAllLines(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}
public myAgenda()
{
InitializeComponent();
readList();
}
private void add_btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(add_txt.Text))
{
MessageBox.Show("Error: Please enter a value");
}
else
{
holder = add_txt.Text;
listBox.Items.Add(ctr + " " + holder);
ctr++;
add_txt.Text = " ";
}
}
private void button1_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach (var item in listBox.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
Application.Exit();
}
答案 0 :(得分:2)
您在listbox
方法中填写readlist
两次,即
第一次:
listBox.Items.AddRange(File.ReadAllLines(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
第二次:
using (StreamReader sr = new StreamReader("save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
您可以删除一种方法中的任何一种来填充内容。第一种方法最好用于可读性。
答案 1 :(得分:1)
您正在listBox上复制内容两次。
尝试这样做:
private void readList()
{
string line;
listBox.Items.Clear();
//Comment out this line then put the File Directory on the StreamReader
//listBox.Items.AddRange(File.ReadAllLines(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"));
using (StreamReader sr = new StreamReader(@"C:\Users\Paul.DESKTOP-HGGDG1D\Desktop\My C# apps\MyAgenda\MyAgenda\MyAgenda\bin\Debug\save.txt"))
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
}
}