You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在删除DataGridView行后同步删除文本文件对应行?

问题:DataGridView删除行同步删除文本文件对应行失败

我是编程新手,正在提升编程能力,遇到了一个无法解决的问题。我的DataGridView加载了文本文件中的数据,设置了删除按钮,希望删除DataGridView中的行的同时同步删除文本文件中的对应行。具体来说,我想删除任意一行(例如第3行),但无法实现文本文件中的行删除操作。我尝试了一些解决方案,但都无效,恳请各位提供帮助。以下是我的代码:

public void deleteBtn_Click(object sender, EventArgs e)
{
    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(path))
    {
        int Countup = 0;
        while (!sr.EndOfStream)
        {
            Countup++;
            if (Countup >= dataGridView1.SelectedRows.Count)
            {
                using (StringWriter sw = new StringWriter(sb))
                {
                    sw.WriteLine(sr.ReadLine());
                }
            }
            else
            {
                sr.ReadLine();
            }
        }
    }
    using (StreamWriter sw = new StreamWriter(path))
    {
        sw.Write(sb.ToString());
    }

    foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
    {
        dataGridView1.Rows.RemoveAt(item.Index);
    }
}

问题分析

你的代码逻辑完全不符合需求:当前判断Countup >= dataGridView1.SelectedRows.Count会跳过前N行(N为选中行数),保留之后所有行,这和"删除指定选中行"的目标完全背离。比如选中1行,代码会跳过文件第一行,保留后续所有行,而不是删除你选中的那一行。

修正方案

假设DataGridView的行与文本文件的行一一对应(无排序、过滤等操作),可以用更简洁可靠的方式实现需求:

public void deleteBtn_Click(object sender, EventArgs e)
{
    // 收集要删除的行索引(DataGridView行索引对应文件行索引)
    HashSet<int> rowsToDelete = new HashSet<int>();
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {
        rowsToDelete.Add(row.Index);
    }

    // 读取文件所有行并过滤掉要删除的行
    List<string> remainingLines = File.ReadAllLines(path)
                                      .Where((line, lineIndex) => !rowsToDelete.Contains(lineIndex))
                                      .ToList();

    // 将剩余行写回文件
    File.WriteAllLines(path, remainingLines);

    // 倒序删除DataGridView行,避免索引错乱
    foreach (DataGridViewRow row in dataGridView1.SelectedRows.Cast<DataGridViewRow>().OrderByDescending(r => r.Index))
    {
        dataGridView1.Rows.Remove(row);
    }
}

注意事项

  • 确保DataGridView行和文件行完全对应,若中途对DataGridView做过排序、筛选,需要重新映射行与文件的对应关系
  • 使用File.ReadAllLines/File.WriteAllLines简化文件操作,减少手动流操作的出错概率
  • 倒序删除DataGridView行:如果正序删除,前面的行被移除后,后续行的索引会前移,导致删除错误
  • 用HashSet存储待删除索引,提升查询效率

内容的提问来源于stack exchange,提问作者Bogdan Şandor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:20:44