c# - 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;
}
}
}
解决方案
...但是当我再次打开 (1) 时,我得到了网格中显示的 csv 的标题行
清除数据表和列:
private void btoDateiOeffnen_Click(object sender, EventArgs e)
{
dt.Clear();
dt.Columns.Clear();
// ... rest of the code ...
推荐阅读
- angular - 使用 Angular Universal 的动态 Web 应用程序(服务器端渲染)
- amazon-web-services - 当我使用 AWS KMS 服务创建签名时,如何使用 java 安全 API 在 AWS 之外验证数字签名?
- google-chrome - 找不到 Chrome 扩展程序的运行位置
- debugging - PhpStorm nodemon 调试 - 不要在断点处停止
- markdown - 使“电子邮件地址”不会变成超链接
- clang - AST 中的表达式大小对于成员访问不正确
- matter.js - MatterJS 允许物体通过但仍然触发碰撞
- php - 文件未在 codeigniter api 中上传
- php - in_array 函数(从文件中读取,而不是在行内)
- ios - Flutter iOS - MediaQuery.of(context).size.width 没有以像素为单位给出宽度