如果我使用了错误的术语,我提前道歉,请随时要求我澄清这个问题是否有任何令人困惑的地方
我正在尝试用 C# 编写一个程序,它做 3 件事:将 4 个文本字段添加到列表框,编辑列表框一条记录中的任何或所有字段,删除所有 4 个字段(在一条记录中)
我将数据存储在文本文件“test1.txt”中,并使用 StreamWriter 写入文件并使用 StreamReader 读取它。我设法添加了记录,但我没有让它删除或编辑记录,这就是我的代码的样子:
string path = "test1.txt";
int index = -1;
public Form1()
{InitializeComponent();}
private void Form1_Load(object sender, EventArgs e)
{
readFile();
}
private void readFile()
{
displayEventsBox.Items.Clear();
StreamReader sr = new StreamReader(path);
string record = sr.ReadLine();
{
displayEventsBox.Items.Add(record);
record = sr.ReadLine();
}
sr.Close();
}
private void displayEventsBox_SelectedIndexChanged(object sender, EventArgs e)
{
index = displayEventsBox.SelectedIndex;
if (index > -1)
{
string record = displayEventsBox.Items[index].ToString();
char[] delim = { ',' };
string[] tokens = record.Split(delim);
txtTaskName.Text = tokens[0];
txtTaskDescription.Text = tokens[1];
txtDateCreated.Text = tokens[2];
txtDateCompleted.Text = tokens[3];
}
}
private void butAddTask_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(path, true);
sw.WriteLine(txtTaskName.Text + "," + txtTaskDescription.Text + "," + txtDateCreated.Text + "," + txtDateCompleted.Text);
sw.Close();
readFile();
clearText();}
private void butEditTask_Click(object sender, EventArgs e)
{
File.Delete(path);
StreamWriter sw = new StreamWriter(path, true);
for (int i = 0; i < displayEventsBox.Items.Count; i++)
{
if (i != index)
{
sw.WriteLine(displayEventsBox.Items[i].ToString());
}
else
{
sw.WriteLine(txtTaskName.Text + "," + txtTaskDescription.Text + "," + txtDateCreated.Text + "," + txtDateCompleted.Text);
}
}
}
private void butDeleteTask_Click(object sender, EventArgs e)
{
File.Delete(path);
StreamWriter sw = new StreamWriter(path, true);
for (int i = 0; i < displayEventsBox.Items.Count; i++)
{
if (i != index)// write from listbox
{
sw.WriteLine(displayEventsBox.Items[i].ToString());
}
}
sw.Close();
readFile();
}
有人可以帮我确定为什么它不允许我删除或更新记录
如果它可以帮助澄清这里是代码 http://collabedit.com/83rev中所有内容的链接