简体   繁体   English

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

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

I am relatively new to c#, I am creating an windows application which would read all the lines from a text file. 我是C#的新手,我正在创建一个Windows应用程序,它将从文本文件读取所有行。 The user will input the string which needs to be replaced in Column[0] and the text with which it needs to be replaced in Column 1 of the DataGridView control. 用户将在DataGridView控件的Column [0]中输入需要替换的字符串,并在第1列中输入需要替换的文本。

I have created two string arrays column0 and column1. 我创建了两个字符串数组column0和column1。 However, I am getting an error while replacing the string in line (column0, column1) 但是,替换行(column0,column1)中的字符串时出现错误

The following is my code: 以下是我的代码:

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

I am using OpenFileDialog to select the file. 我正在使用OpenFileDialog选择文件。

The Error While Executing: 执行时的错误: 在此处输入图片说明

Stuartd is correct… there are more lines in the file than there are elements to search. Stuartd是正确的…文件中的行比要搜索的元素还多。 I am not sure what the search is doing in a sense that it seems somewhat limited. 从某种程度上看,我不确定搜索在做什么。 The code appears to search for each item depending on what line it is. 该代码似乎根据每行搜索每个项目。 The searched value in column 0 and the replace value in column 1 of row 0… will only replace those values for the FIRST line in the file. 在第0列的第0列中搜索的值和在第0行的第1列中的替换值…将仅替换文件中FIRST行的那些值。 The DataGridView s second row values will search/replace only the SECOND line and so on. DataGridView的第二行值将仅搜索/替换第二行,依此类推。 This seems odd. 这似乎很奇怪。

Example the two string arrays (column0 and column1) have sizes set to the number of rows in dgvMapping . 例如,两个字符串数组(column0和column1)的大小设置为dgvMapping的行dgvMapping Let's say there are 5 rows in the grid, then the array sizes will be 5 strings. 假设网格中有5行,那么数组大小将为5个字符串。 When you start the loop to write the strings, the loop starts at 0 and stops at the number of lines in the file. 当您开始循环以编写字符串时,循环从0开始,并在文件中的行数处停止。 The code uses this i variable as an index into the two arrays. 代码使用此i变量作为两个数组的索引。 If there are more lines in the file, than there are rows in the grid… then you will get the error. 如果文件中的行多于网格中的行,那么您将得到错误。

Again, this seems odd to do the search and replace this way. 同样,进行搜索并以这种方式替换似乎很奇怪。 Assuming you want to search for EACH term in all the rows in column 0 and replace the found searched string with the replace string in column 1, then you will need to loop through EACH row of the grid for EACH line in the file. 假设您要在第0列的所有行中搜索EACH术语,并用第1列中的替换字符串替换找到的搜索字符串,那么您将需要遍历网格的EACH行以找到文件中的EACH行。 This will replace ALL the search/replace terms in the grid with ALL the lines in the file. 这将用文件中的所有行替换网格中的所有搜索/替换项。 If this is what you what to accomplish below is one way to achieve this, however…there are possibly better ways to accomplish this. 如果这是您要完成的任务,则下面是实现此目的的一种方法,但是……可能有更好的方法可以实现此目的。

The code below reads the file into one big string. 下面的代码将文件读取为一个大字符串。 Then the code loops through ALL the grid rows to search/replace the strings in the big string. 然后,代码循环遍历所有网格行以搜索/替换大字符串中的字符串。 Hope this helps. 希望这可以帮助。

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

You are looping around a file of unknown number of lines, and assuming that the count of lines in the grid is exactly the same as that of the file. 您正在绕行的行数未知,并假定网格中的行数与文件的行数完全相同。 Your code will only work if both the file and the gridView have the same number of lines. 仅当文件和gridView的行数相同时,您的代码才有效。

One of the solutions, is to loop over the array of lines (as you have already did), and search for the GridViewRow in which the current line contains a key in your DGV. 解决方案之一是遍历行数组(就像您已经做过的那样),并搜索GridViewRow,其中当前行在DGV中包含一个键。 If this is the case, then replace all the occurences of the key by the value (obtained from the gridView) in that line, otherwise do nothing. 如果是这种情况,请用该行中的值(从gridView获取)替换所有出现的键,否则不执行任何操作。

Check out the code below : 查看以下代码:

// 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