函数返回一个空的数据表,但我可以看到"individual"元素正在导入



我在使用 C# 中的函数时遇到了几个小时的麻烦。基本上,我想调用一个带有文件的函数(在这种情况下是一个.csv文件,带有;分隔的列(,并将.csv文件中包含的数据作为DataTable返回(包含标题的第一行除外(。为此,我尝试过:

private DataTable getDataTable(string file)
{
    DataTable tbl = new DataTable("Order_proposal_Internal_External");
    tbl.Columns.Add(new DataColumn("FileName"));
    tbl.Columns.Add(new DataColumn("Supplier"));
    tbl.Columns.Add(new DataColumn("Store"));
    tbl.Columns.Add(new DataColumn("Item"));
    tbl.Columns.Add(new DataColumn("Quantity"));
    tbl.Columns.Add(new DataColumn("Delivery_Date"));  
    string[] lines = System.IO.File.ReadAllLines(file);
    lines = lines.Skip(1).ToArray();
    foreach (string line in lines)
    {
        var cols = line.Split(';');
        if (cols.Length == 1)
            continue;
        DataRow dr = tbl.NewRow();
        dr[0] = file;
        for (int cIndex = 1; cIndex + 1 < tbl.Columns.Count; cIndex++)
        {
            dr[cIndex + 1] = cols[cIndex];
            MessageBox.Show(cols[cIndex]);
        }
    }
    return tbl;
}

在这里我可以看到MessageBox.Show(cols[cIndex]);获取所有数据,除了第一行(包含标题,这是预期的(。包含文件名的第一列不包含在输出中(这不是有意的(。

当我将其作为一个整体打印出来时,表格本身也是空的。这也在稍后阶段得到确认,我调用另一个函数,其中我使用此表作为参数t并且:

if (t.Rows == 0)
{
     MessageBox.Show("Fails at Point 5");
     return;
}

当我运行该程序时,它会打印Fails at Point 5.

用作函数参数的.csv文件具有以下外观:

supplier;store;item;quantity;delivery_date
13;1;411;12.0;20170322
80;1;415;3.0;20170322

有没有人知道我没有掌握什么?

tbl.NewRow()创建新的TableRow对象,但不将其添加到表的Rows集合中。它完全按照锡上所说的去做,仅此而已。将其添加到Rows是一个单独的方法调用。

    DataRow dr = tbl.NewRow();
    dr[0] = file;
    for (int cIndex = 1; cIndex + 1 < tbl.Columns.Count; cIndex++)
    {
        dr[cIndex + 1] = cols[cIndex];
    }
    //  Now that it's populated, add it to the table. 
    tb.Rows.Add(dr);

您错过了将行添加到 DataTable.Rows 集合的调用,仅创建 DataRow 不会将其添加到 Rows 集合,并且表仍为空。

DataRow dr = tbl.NewRow();
dr[0] = file;
for (int cIndex = 1; cIndex + 1 < tbl.Columns.Count; cIndex++)
{
    dr[cIndex + 1] = cols[cIndex];
    MessageBox.Show(cols[cIndex]);
}
tbl.Rows.Add(dr);   // < this one is needed

这条线似乎也是错误的

dr[cIndex + 1] = cols[cIndex];

在这里,循环开始从索引 2(存储(处的列设置加载的值,跳过索引 1(供应商(处的列,它应该是

dr[cIndex] = cols[cIndex-1];

请注意,拆分字符串(供应商代码(中的第一个元素位于索引零处,因此您应该从 cIndex-1 读取。

也是 for.. 的结束条件。循环不正确。在 CSV 文件中,您有 5 列,在表中有 6 列。循环应该与

for (int cIndex = 1; cIndex < tbl.Columns.Count; cIndex++)
{
   dr[cIndex] = cols[cIndex-1];
   ....
}

您需要将行添加到数据表中。在 DataTable 对象上调用 NewRow 方法时,它将创建具有与行定义匹配的架构的行,但实际上并未将其添加到其内部集合中。

        tbl.Rows.Add(dr);

相关内容

最新更新