【问题标题】:c# Read lines from a file and replace with text from DataGridView Datac# 从文件中读取行并用 DataGridView 数据中的文本替换
【发布时间】:2017-04-28 10:34:19
【问题描述】:

我对 c# 比较陌生,我正在创建一个 Windows 应用程序,它将读取文本文件中的所有行。用户在DataGridView控件的Column[0]中输入需要替换的字符串,在Column1中输入需要替换的文本。

我创建了两个字符串数组column0 和column1。 但是,在替换行中的字符串时出现错误 (column0, column1)

以下是我的代码:

        string[] column0 = new string[dgvMapping.Rows.Count];
        string[] column1 = new string[dgvMapping.Rows.Count];
        int j = 0;
        foreach(DataGridViewRow row in dgvMapping.Rows)
        {
            if (!string.IsNullOrEmpty(Convert.ToString(row.Cells[0].Value)))
            {
                column0[j] = Convert.ToString(row.Cells[0].Value);
                column1[j] = Convert.ToString(row.Cells[1].Value);
                j++;
            }
        }

        var _data = string.Empty;

        String[] arrayofLine = File.ReadAllLines(ofd.FileName);

        using (StreamWriter sw = new StreamWriter(ofd.FileName + ".output"))
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                string line = arrayofLine[i];
                line = line.Replace(column0[i], column1[i]);
                sw.WriteLine(line);
            }
        }

我正在使用 OpenFileDialog 来选择文件。

执行时的错误:

【问题讨论】:

  • “我遇到了一个错误” - 如果你能说明实际的错误是什么,这会有所帮助。
  • @stuartd 我已经更新了错误的帖子
  • 现在使用调试器找出哪一行引发了异常
  • @stuartd 这一行:line = line.Replace(column0[i], column1[i]);
  • 所以看起来您的文件中的行数比 DGV 中的行数多

标签: c# winforms datagridview


【解决方案1】:

您正在循环一个未知行数的文件,并假设网格中的行数与文件的行数完全相同。仅当文件和 gridView 的行数相同时,您的代码才有效。

其中一个解决方案是遍历行数组(就像您已经做过的那样),并搜索当前行包含 DGV 中的键的 GridViewRow。如果是这种情况,则将所有出现的键替换为该行中的值(从 gridView 获得),否则什么也不做。

查看下面的代码:

// Convert the row collection to a list, so that we could query it easily with Linq
List<DataGridViewRow> mySearchList = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
const int KEY_INDEX = 0; // Search index in the grid
const int VALUE_INDEX = 1; // Value (replace) index in the grid
for (int i = 0; i < arrayofLines.Length; i++)
{

    string line = arrayofLines[i];

    // Get data grid view Row where this line contains the key string
    DataGridViewRow matchedRow = mySearchList.FirstOrDefault(obj => line.Contains(obj.Cells[KEY_INDEX].Value.ToString()));
    // If this row exists, replace the key with the value (obtained from the grid)
    if (matchedRow != null)
    {
        string key = matchedRow.Cells[KEY_INDEX].Value.ToString();
        string value = matchedRow.Cells[VALUE_INDEX].Value.ToString();

        line = line.Replace(key, value);

        sw.WriteLine(line);
    }
    else
    {
        // Otherwise, do nothing
    }
}

【讨论】:

    【解决方案2】:

    Stuartd 是正确的……文件中的行数多于要搜索的元素数。从某种意义上说,我不确定搜索在做什么,它似乎有些有限。该代码似乎根据它所在的行搜索每个项目。第 0 列中的搜索值和第 0 行第 1 列中的替换值……只会替换文件中第一行的那些值。 DataGridViews 第二行值将仅搜索/替换第二行,依此类推。这似乎很奇怪。

    例如,两个字符串数组(column0 和column1)的大小设置为dgvMapping 中的行数。假设网格中有 5 行,那么数组大小将是 5 个字符串。当您启动循环以写入字符串时,循环从 0 开始并在文件中的行数处停止。代码使用这个i 变量作为两个数组的索引。如果文件中的行数多于网格中的行数……那么您将收到错误消息。

    同样,以这种方式进行搜索和替换似乎很奇怪。假设您要在第 0 列的所有行中搜索每个术语,并将找到的搜索字符串替换为第 1 列中的替换字符串,那么您将需要遍历网格的每一行以查找文件中的每一行。这将用文件中的所有行替换网格中的所有搜索/替换术语。如果这是您要完成的事情,那么下面是实现这一目标的一种方法,但是……可能有更好的方法来实现这一目标。

    下面的代码将文件读入一个大字符串。然后代码循环遍历所有网格行以搜索/替换大字符串中的字符串。希望这会有所帮助。

     string bigString = File.ReadAllText(ofd.FileName);
      try {
        using (StreamWriter sw = new StreamWriter(ofd.FileName + ".output")) {
          for (int k = 0; k < dgvMapping.Rows.Count; k++) {
            if (dgvMapping.Rows[k].Cells[0].Value != null && dgvMapping.Rows[k].Cells[1].Value != null) {
              string searchTerm = dgvMapping.Rows[k].Cells[0].Value.ToString();
              string replaceTerm = dgvMapping.Rows[k].Cells[1].Value.ToString();
              if (searchTerm != "") {
                bigString = bigString.Replace(searchTerm, replaceTerm);
              } else {
                // one of the terms is empty
              }
            } else {
              // one of the terms is null}
            }
          }
          sw.WriteLine(bigString);
        }
      }
      catch (Exception ex) {
        MessageBox.Show("Write Erro: " + ex.Message);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多