当我将文本文件导入其中时,DataGridView会创建额外的行。

时间:2017-04-26 11:06:31

标签: c# datagridview

我尝试将.txt文件导入DataGrid。问题是虽然代码工作正常,但是在导入.txt文件时,它会创建额外的行,例如this;

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.DefaultExt = ".txt";
        ofd.InitialDirectory = @"C:\Users\Cabbaa\Desktop";
        DialogResult a = ofd.ShowDialog();
        var lines = File.ReadAllLines(ofd.FileName);
        if (lines.Count() > 0)
        {
            foreach (var columnName in lines.FirstOrDefault()
                .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
            {
                dataGridView1.Rows.Add(Time, Class);
            }
            foreach (var cellValues in lines)
            {
                var cellArray = cellValues
                    .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
                if (cellArray.Length == dataGridView1.Columns.Count)
                    dataGridView1.Rows.Add(cellArray);
            }
        }

1 个答案:

答案 0 :(得分:0)

您的问题在于代码的第一个foreach循环。

        //you are adding rows to the column here, you are not adding headers 
        foreach (
          var columnName in 
          lines.FirstOrDefault().Split(new[] {','}, 
          StringSplitOptions.RemoveEmptyEntries)
        )
        {
            //since we split the line on commas, 
            //we are adding a row to the table for every 
            //CSV value we found in the current line. 
            //this is causing the "garbage" rows you are seeing
            //i do not know where "Time" and "Class" come from here. 
            //they weren't part of that first line in this example. 
            //my guess is you do not need this loop at all.
            //since the headers already neatly show up on the table in your screenshot.
            dataGridView1.Rows.Add(Time, Class);
        }

        //this works just fine.
        foreach (var cellValues in lines)
        {
            var cellArray = cellValues
                .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
            if (cellArray.Length == dataGridView1.Columns.Count)
                dataGridView1.Rows.Add(cellArray);
        }