【问题标题】:Compare column of datatable with if statement将数据表的列与 if 语句进行比较
【发布时间】:2013-09-25 01:22:30
【问题描述】:

我需要导入 CSV 文件,然后上传到数据表中。然后我需要验证该列是否满足要求,并确保最终用户以正确的格式导入。在 CSV 文件中必须有 3 列,即 item、price 和 measure。

当我尝试将列名与字符串进行比较时,错误开始,这里是代码 sn-p。

private bool verifyColumn(DataTable dt)
{
    /* Column 
     * 1) items
     * 2) price
     * 3) measure
    */

    foreach (DataColumn col in dt.Columns)
    {  
        if (col.ColumnName.ToString() == "price")
        {
            continue;
        }
        else if (col.ColumnName.ToString() == "item")
        {
            continue;
        }
        else if (col.ColumnName.ToString() == "measure")
        {
            continue;
        }
        else
        {
            return false;
        }                           
    }

    return true;
}

在调试模式下,第一个循环是 show 'item' 但不能在 if 语句中捕获。我该如何解决这个问题?

使用A Portable and Efficient Generic Parser for Flat Files将CSV文件导入数据表的代码。

GenericParserAdapter paste = new GenericParserAdapter(fileName);                    
paste.FirstRowHasHeader = true;
paste.ColumnDelimiter = ';';

DataTable dt dt = paste.GetDataTable();
if (dt.Columns.Count != 3)
{ 
    MessageBox.Show(errorMessage, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
    dt.Clear();
    return;
}

// Here to do verify columт

【问题讨论】:

    标签: c# winforms csv ado.net datatable


    【解决方案1】:

    在我看来,第一列是“item”,但您按“item”过滤。

    P/S:您应该创建一个变量来保存 col.ColumnName.ToString() 值。 (鉴于 ColumnName 不是字符串,这有点奇怪)

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 2021-05-06
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多