C# 在读取其值之前验证 DataRow 中是否存在列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10432126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:50:27  来源:igfitidea点击:

Verify that a column exists in the DataRow before reading its value

c#

提问by CrBruno

How do I write code that reads a DataRow but, if filed in DataRow isn't there, it just skips it and moves on, like this for example:

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

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

Now, the Column BarcodeIssueUnitcan belong to the table but, in some cases, that column does not exist in the table. If it's not there and I read it, I get this error:

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

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

I just want to run a check if the column is there ok, let see the values, if it's not, just skip that part and go on.

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

回答by Nikhil Agrawal

Check for column name using DataRow.Table.Columns. If there convert value else come out.

使用DataRow.Table.Columns. 如果有转换值其他的出来。

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

回答by Shai

You can check if the table scheme for the current row contains a specific column:

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

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

回答by Tim Schmelter

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

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