因此,我是C#中的新手,我的程序中有這個列表框,它正在複製它從文本框中讀取的內容。 每當我啓動我的程序時,它會將save.txt文件的內容加載到列表框中,但是當它執行時,它會加載所有save.txt內容的副本。我在加載內容之前嘗試清除列表框,但它不起作用。我的程序是從文本框C複製輸入流#
這裏是我的代碼:
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();
}
被再次複製整個流或重複剛剛進入其填充在save.txt的條目? –