Check if DataRow exists by column name in c#?

C#NullDatarow

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

You should try

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

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

Solution 2 - C#

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.

Solution 3 - C#

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";
}

Solution 4 - C#

You can use

try {
   user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
   // do something if you want 
}

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwaqasahmedView Question on Stackoverflow
Solution 1 - C#KibbeeView Answer on Stackoverflow
Solution 2 - C#JeffPGMTView Answer on Stackoverflow
Solution 3 - C#Allan WolffView Answer on Stackoverflow
Solution 4 - C#ShuoView Answer on Stackoverflow
Solution 5 - C#Big EndianView Answer on Stackoverflow