25

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:

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

Now, the Column BarcodeIssueUnit can 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:

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.

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
CrBruno
  • 963
  • 8
  • 18
  • 33
  • VB, still a duplicate: http://stackoverflow.com/questions/1984893/how-to-check-if-a-column-with-a-given-name-exists-in-a-datarow – nawfal Sep 21 '13 at 12:22
  • Possible duplicate of [How can I validate if the column exist in a DataRow object?](http://stackoverflow.com/questions/9677852/how-can-i-validate-if-the-column-exist-in-a-datarow-object) – C-Pound Guru Nov 15 '15 at 16:07

3 Answers3

51

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

BarcodeIssueUnit = dr_art_line.Table.Columns.Contains("BarcodeIssueUnit")?
                   dr_art_line["BarcodeIssueUnit"].ToString(): "";
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
5
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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

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();
 }
Shai
  • 25,159
  • 9
  • 44
  • 67