gpt4 book ai didi

c# - 当我将文本文件导入 DataGridView 时,DataGridView 会创建额外的行。

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:53 25 4
gpt4 key购买 nike

我正在尝试将 .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);
}
}

最佳答案

您的问题出在代码的第一个 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);
}

关于c# - 当我将文本文件导入 DataGridView 时,DataGridView 会创建额外的行。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43632419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com