簡體   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