【问题标题】:Verify that a column exists in the DataRow before reading its value在读取其值之前验证 DataRow 中是否存在列
【发布时间】:2012-05-13 00:17:30
【问题描述】:

如何编写读取 DataRow 的代码,但如果 DataRow 中的文件不存在,它会跳过它并继续前进,例如:

string BarcodeIssueUnit;
if (dr_art_line["BarcodeIssueUnit"].ToString().Length <= 0)
{
    BarcodeIssueUnit = "";
}
else
{
    BarcodeIssueUnit = dr_art_line["BarcodeIssueUnit"].ToString();
}

现在,列 BarcodeIssueUnit 可以属于表,但在某些情况下,表中不存在该列。如果它不存在并且我阅读了它,我会收到此错误:

System.ArgumentException: Column `BarcodeIssueUnit` 
does not belong to table Line.

我只是想检查一下列是否正常,让我们看看值,如果不是,跳过那部分继续。

【问题讨论】:

标签: c#


【解决方案1】:

使用DataRow.Table.Columns 检查列名。如果有convert value else出来。

BarcodeIssueUnit = dr_art_line.Table.Columns.Contains("BarcodeIssueUnit")?
                   dr_art_line["BarcodeIssueUnit"].ToString(): "";

【讨论】:

    【解决方案2】:

    您可以检查当前行的表方案是否包含特定列:

     if (!dr_art_line.Table.Columns.Contains("BarcodeIssueUnit"))
     {
         BarcodeIssueUnit = "";
     }
     else
     {
          BarcodeIssueUnit = dr_art_line["BarcodeIssueUnit"].ToString();
     }
    

    【讨论】:

      【解决方案3】:
      if(dr_art_line.Table.Columns.Contains("BarcodeIssueUnit"))
      {
          BarcodeIssueUnit = dr_art_line.Field<String>("BarcodeIssueUnit");
      }
      else
      {
          BarcodeIssueUnit = String.Empty;
      }
      

      http://msdn.microsoft.com/en-us/library/system.data.datacolumncollection.contains.aspx

      【讨论】:

        猜你喜欢
        • 2012-10-02
        • 1970-01-01
        • 2010-11-01
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 2021-06-03
        • 2020-09-12
        • 1970-01-01
        相关资源
        最近更新 更多