[c#] Check if DataRow exists by column name in c#?

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?

This question is related to c# null datarow

The answer is


You can use

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

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.


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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"

Examples related to datarow

Find row in datatable with specific id DataColumn Name from DataRow (not DataTable) How to add new DataRow into DataTable? Simple way to copy or clone a DataRow? get index of DataTable column with name Getting datarow values into a string? DataRow: Select cell value by a given column name Check if DataRow exists by column name in c#? How do I get column names to print in this C# program? C# DataRow Empty-check