How to read /load text (*.txt) file values in datagridview using C# ..?

后端 未结 3 1666
北恋
北恋 2021-01-20 14:53

can anyone help me..?

Here, i need to read/load text (*.txt) file values in my datagridview. this is that sample text file, which i need to load.

 S.         


        
3条回答
  •  耶瑟儿~
    2021-01-20 15:27

    One way to do it is:

    var lines = File.ReadAllLines("input.txt");
    if (lines.Count() > 0)
    {
        foreach (var columnName in lines.FirstOrDefault()
            .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
        {
            dataGridView1.Columns.Add(columnName, columnName);
        }
        foreach (var cellValues in lines.Skip(1))
        {
            var cellArray = cellValues
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (cellArray.Length == dataGridView1.Columns.Count)
                dataGridView1.Rows.Add(cellArray);
        }
    }
    

    Of course, this works for the sample input file that you provided. Any variation to that format would require further validation and an increase in code complexity.

提交回复
热议问题