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

后端 未结 3 1579
北恋
北恋 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:13

    Try this..

    System.IO.StreamReader file = new System.IO.StreamReader("yourfile.txt");
    string[] columnnames = file.ReadLine().Split(' ');
    DataTable dt = new DataTable();
    foreach (string c in columnnames)
    {
        dt.Columns.Add(c);
    }
    string newline;
    while ((newline = file.ReadLine()) != null)
    {
        DataRow dr = dt.NewRow();
        string[] values = newline.Split(' ');
        for (int i = 0; i < values.Length; i++)
        {
            dr[i] = values[i];
        }
        dt.Rows.Add(dr);
    }
    file.Close();
    dataGridView1.DataSource = dt;
    

    And don't be discouraged, but this is not the proper way to ask a question out here on SO. Please get yourself familiar first.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-20 15:36
            this.Size = new Size(750, 450);
            data.Size = new Size(700, 200);
            data.Location = new Point(5, 40);
    
            string[] raw_text = System.IO.File.ReadAllLines("Etudiant.txt");
            string[] data_col = null;
    
            int x = 0;
    
            foreach (string text_line in raw_text) {
                //MessageBox.Show(text_line);
                data_col = text_line.Split('|');
    
                if (x == 0){
                    //header
                    for (int i=0; i <= data_col.Length - 1; i++) {
                        table.Columns.Add(data_col[i]);
                    }
                    x++;
                }
                else {
                    //data
                    table.Rows.Add(data_col);
                }
            }
    
            data.DataSource = table;
            this.Controls.Add(data);
    
    0 讨论(0)
提交回复
热议问题