118

I want to do something like this:

   private User PopulateUsersList(DataRow row)
        {
            Users user = new Users();
            user.Id = int.Parse(row["US_ID"].ToString());
            if (row["US_OTHERFRIEND"] != null)
            {
                user.OtherFriend = row["US_OTHERFRIEND"].ToString();
            }
            return user;
        }

However, I get an error saying US_OTHERFRIEND does not belong to the table. I want to simply check if it is not null, then set the value.

Isn't there a way to do this?

Irshad
  • 3,071
  • 5
  • 30
  • 51
waqasahmed
  • 3,555
  • 6
  • 32
  • 52

5 Answers5

319

You should try

if (row.Table.Columns.Contains("US_OTHERFRIEND"))

I don't believe that row has a columns property itself.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
Kibbee
  • 65,369
  • 27
  • 142
  • 182
22
if (drMyRow.Table.Columns["ColNameToCheck"] != null)
{
   doSomethingUseful;
{
else { return; }

Although the DataRow does not have a Columns property, it does have a Table that the column can be checked for.

JeffPGMT
  • 239
  • 2
  • 3
9

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}
Allan Wolff
  • 91
  • 1
  • 1
-6

You can use

try {
   user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
   // do something if you want 
}
Shuo
  • 4,749
  • 9
  • 45
  • 63
-8
if (row.Columns.Contains("US_OTHERFRIEND"))
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Big Endian
  • 944
  • 1
  • 6
  • 23