在读取列的值之前,验证数据行中是否存在该列

本文关键字:数据 存在 验证 是否 读取 | 更新日期: 2023-09-27 18:33:07

如何编写读取 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.

我只想检查列是否存在正常,让我们看看值,如果没有,请跳过该部分并继续。

在读取列的值之前,验证数据行中是否存在该列

使用 DataRow.Table.Columns 检查列名。如果有转换值,其他值就会出来。

BarcodeIssueUnit = dr_art_line.Table.Columns.Contains("BarcodeIssueUnit")?
                   dr_art_line["BarcodeIssueUnit"].ToString(): "";
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

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

 if (!dr_art_line.Table.Columns.Contains("BarcodeIssueUnit"))
 {
     BarcodeIssueUnit = "";
 }
 else
 {
      BarcodeIssueUnit = dr_art_line["BarcodeIssueUnit"].ToString();
 }
相关文章: