繁体   English   中英

c#从文件中读取行并替换为DataGridView Data中的文本

[英]c# Read lines from a file and replace with text from DataGridView Data

我是C#的新手,我正在创建一个Windows应用程序,它将从文本文件读取所有行。 用户将在DataGridView控件的Column [0]中输入需要替换的字符串,并在第1列中输入需要替换的文本。

我创建了两个字符串数组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是正确的…文件中的行比要搜索的元素还多。 从某种程度上看,我不确定搜索在做什么。 该代码似乎根据每行搜索每个项目。 在第0列的第0列中搜索的值和在第0行的第1列中的替换值…将仅替换文件中FIRST行的那些值。 DataGridView的第二行值将仅搜索/替换第二行,依此类推。 这似乎很奇怪。

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

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

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

 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);
  }

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

解决方案之一是遍历行数组(就像您已经做过的那样),并搜索GridViewRow,其中当前行在DGV中包含一个键。 如果是这种情况,请用该行中的值(从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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM