C# 当我将文本文件导入DataGridView时,它会创建额外的行。
我正在尝试将.txt文件导入DataGrid。问题是,尽管代码基本正常,但在导入.txt文件时,它会创建额外的行,比如C# 当我将文本文件导入DataGridView时,它会创建额外的行。,c#,datagridview,C#,Datagridview,我正在尝试将.txt文件导入DataGrid。问题是,尽管代码基本正常,但在导入.txt文件时,它会创建额外的行,比如 您的问题在于代码的第一个foreach循环 //you are adding rows to the column here, you are not adding headers foreach ( var columnName in lines.FirstOrDefault().Split(new[
您的问题在于代码的第一个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);
}
你是说底部那一排空的吗?(我认为这是datagrid的“添加新记录行”。您可以通过设置
datagrid.allowUserToAddress=false
来关闭它)哦,不,前两个。我想如果你查看我链接的imgur文件,你就能看到它们。啊!我看到了,等等,我试过了。前两行仍然损坏。但这次,它跳过了我的第一行,共3行。当我将skip值设置为0时,显示了我所有的3个条目,但前两行仍然保留。我找出了原因并更新了答案。有趣的是,前两行在技术上并没有“损坏”。编译第一个循环的唯一原因是Time
和Class
解析为现有的类定义或实例。datagrid单元格中的值是这些定义的命名空间和类名。
//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);
}