将两个文本文件合并在一起后,C#datagridview没有显示文本文件中的完整数据

时间:2018-04-05 06:02:17

标签: c#

在我将两个文本文件合并在一起并尝试在我的datagridview中读取合并文件后,我确实意识到我的datagridview没有显示我的文本文件的完整数据。

这是调试后的数据网格视图。enter image description here

这是我合并后的文本文件格式。(我不能按顺序合并文件,因为我还是新编码) enter image description here

这是我的代码。

 private bool loadTxt()
    {
        // try locate the txt file, exist or not
        try
        {
            StreamReader rrr = new StreamReader("merge.txt");
            rrr.Close();
        }
        catch (FileNotFoundException ex)
        {
            return false;
        }

        // read all line from txt file
        var file = File.ReadAllLines("merge.txt");
        string DateTag = "<Date>";
        string NIDTag = "<News ID>";
        string StockIDTag = "<StockID>";
        string LatestPriceTag = "<Latest Price>";
        string TargetPriceTag = "<Target Price>";
        string StockComTag = "<StockCompany>";

        string Date = "";
        string NID = "";
        string StockID = "";
        string LatestPrice = "";
        string TargetPrice = "";
        string StockCom = "";

        int row = dataGridView2.Rows.Count - 1;

        // Loop through the file and find targeted data to store in datagridview1
        for (int i = 0; i < file.Length - 1; i++)
        {
            if (file[i] == DateTag)
            {
                dataGridView2.Rows.Add();
                Date = file[i + 1];
                dataGridView2.Rows[row].Cells[0].Value = Date;
            }

            if (file[i] == NIDTag)
            {
                NID = file[i + 1];
                dataGridView2.Rows[row].Cells[1].Value = NID;
            }

            if (file[i] == StockIDTag)
            {
                StockID = file[i + 1];
                dataGridView2.Rows[row].Cells[2].Value = StockID;
            }

            if (file[i] == LatestPriceTag)
            {
                LatestPrice = file[i + 1];
                dataGridView2.Rows[row].Cells[3].Value = LatestPrice;
            }

            if (file[i] == TargetPriceTag)
            {
                TargetPrice = file[i + 1];
                dataGridView2.Rows[row].Cells[4].Value = TargetPrice;       
            }

            if (file[i] == StockComTag)
            {
                StockCom = file[i + 1];
                dataGridView2.Rows[row].Cells[5].Value = StockCom;
                row++;
            }
        }

        return true;
    }

感谢。

1 个答案:

答案 0 :(得分:0)

我认为您正在向同一行添加数据

int row = dataGridView2.Rows.Count - 1;  //your row 

并使用row将每个值添加到dataGridView2

if (file[i] == DateTag)
            {
                dataGridView2.Rows.Add();
                Date = file[i + 1];
                dataGridView2.Rows[row].Cells[0].Value = Date; //same [row]
            }
希望它有所帮助!!