首页 > 解决方案 > c# OpenFileDialog, Streamreader, Datatable, skip first line after open next file

问题描述

Sorry I´m a Beginner and i have read many threads here on stackoverflow but i don´t came to an result for me ... In my Code i open a File Dialog to open a csv-file. My (1)csv-file has a header includet and another (2)csv-file is without header.

ProgrammStart: When i open (1) everything is ok in the datagridview(dgv), but when i open (1) again, then i got the headerline of the csv shown in the grid. :ProgrammClose

ProgrammStart: When i open (2) first line is missing... when i open (2) again, everything is fine. :ProgrammClose

Maybe someone can be so friendly and show me what i can do cause i tried many many examples but none was given the wanted result.

 private void btoDateiOeffnen_Click(object sender, EventArgs e)
    {
        dt.Clear();

        if (oFDcsv.ShowDialog() == DialogResult.OK)
        {

            using (StreamReader sr = new StreamReader(oFDcsv.FileName, Encoding.UTF8))
            {

                // bis Dateiende lesen
                while (!sr.EndOfStream)
                {
                    // Zeile einlesen und anhand des Trennzeichens ";" in einzelne Spalten (stringarray) splitten
                    string[] currentline = sr.ReadLine().Replace(",",".").Split(new string[] { ";" }, StringSplitOptions.None);

                    // wenn neue Tabelle (noch keine Spalten enthalten)

                    if (dt.Columns.Count == 0)
                    {
                        // n Spalten der ersten gelesenen Zeile hinzufügen
                        // als Spaltenüberschrift aufsteigende Zahlen beginnend mit 1
                        for (int i = 0; i < currentline.Length; i++)
                        {
                            dt.Columns.Add(Convert.ToString(i + 1));
                            //dt.Columns.Add(currentline[i]);                                
                        }
                    }
                    else
                    {
                            dt.Rows.Add(currentline);
                    }                        
                }
                sr.Close();
            }

            // DataGridView befüllen
            dgvDateiAnsicht.DataSource = dt;

            // DataGridView dritte Spalte ausblenden
            dgvDateiAnsicht.Columns[2].Visible = false;

            // DataGridView Spalten sortieren unterbinden
            foreach (DataGridViewColumn column in dgvDateiAnsicht.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;                    
            }
        }
    }

标签: c#datatablestreamreader

解决方案


...但是当我再次打开 (1) 时,我得到了网格中显示的 csv 的标题行

清除数据表列:

private void btoDateiOeffnen_Click(object sender, EventArgs e)
{
    dt.Clear();
    dt.Columns.Clear();
    // ... rest of the code ...

推荐阅读