C#使用文本框从文本文件中删除一行文本

时间:2017-08-10 17:58:54

标签: c#

C#可以用文本框中的用户输入替换文本文件中的单行文字吗?

我的文本文件有多个具有相同名称的字符串" Ang Mo Kio"

我的计划应该是一家自行车租赁公司,向客户租用自行车。我要求显示位置。默认位置设置为" Ang mo kio",因此我使用StreamWriter将其写入文本文件。

private void button1_Click(object sender, EventArgs e)
{
    StreamWriter location = new StreamWriter("C:\\temp\\Mb.txt", true); 
    location.WriteLine(textBox7.Text);
    location.Close();
 }

并将其与我的组合框相关联,这样当我点击组合框索引时,它会根据阅读线显示文本框中的位置。

if (comboBox1.SelectedIndex >= 0)
{
    string filename = ("C:\\temp\\Mb.txt");
    string[] lines = File.ReadAllLines(filename);

    textBox2.Text = (lines[comboBox1.SelectedIndex]);
}

现在我试图出租自行车,但是当我在combobox1中选择索引后点击一个按钮时,我删除了索引,以便下一个客户无法将其出租。

string X;

int index;
index = comboBox1.SelectedIndex;
if (index != -1)
{
    X = comboBox1.Items[index].ToString();
    comboBox1.Items.RemoveAt(index);
}


using (StreamWriter sw1 = new StreamWriter("C:\\temp\\MountainBike.txt"))
{
    foreach (var item in comboBox1.Items)
    {
        sw1.WriteLine(item);
    }
    this.Close();
}

现在主要的问题是我的位置保持不变,我无法从文本框中显示的内容中删除一行,并且它仍保留在我的文本文件中。

我尝试使用StreamWriter来覆盖它,但它只删除了所有行 - 而不是一行。

1 个答案:

答案 0 :(得分:0)

虽然我从一开始就意识到它有点不同,但这里有一个建议如何破解你的结构的解决方案。

从文本框中取出文本并将其拆分为单行:

List<string> allLines = textBox2.Text.Split('\n').ToList();

现在使用与组合框选择相同的索引来删除列表中的文本(如果我记得,顺序是相同的?=!)

X = comboBox1.Items[index].ToString();
comboBox1.Items.RemoveAt(index);
allLines.RemoveAt(index);

再次将文本重新插入

textBox2.Text = String.Join("\n", allLines);

编辑:

可能更好的解决方案是将文件加载为List<string>

List<string> lines = File.ReadAllLines(filename).ToList();

这将允许您使用组合框的选定索引直接在源处删除行,并将其立即重新写入文件。通过这种方式,您可以使用更新的源代码,并且可以继续使用组合框中的索引(因为lines和组合框将具有与我理解的相同的项目。如果我错了,请纠正我。

comboBox1.Items.RemoveAt(index);
lines.RemoveAt(index);
textBox2.Text = (lines[comboBox1.SelectedIndex]);