How to check if a column exists in a datarow?

Hi,

I'm performing some tasks on a DataRow - retrieving values etc, but I want to be able to check that a row exists, for example

name = row["name"].ToString()

but how can I check that row["name"] actually exists?

There's no 'Contains' method I can use?

Thanks

Wint.
LVL 9
WinterMuteUKAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
TheAvengerConnect With a Mentor Commented:
public static string GetNameFromDataRow(DataRow row)
{
     if(row.Table.Columns["name"] != null)
          return row["name"].ToString();
     else return null;
}
0
 
rohanpandyaCommented:
Hi

 Use following

    objDataset.Tables[0].Columns["name"] != null
0
 
rohanpandyaCommented:
put about code in if condition or any where it's work fine

 Best Luck
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
TheAvengerCommented:
if (!row.IsNull ("name"))
   name = row["name"].ToString();
else
   name = "Name does not exist";
0
 
WinterMuteUKAuthor Commented:
Doesn't IsNull say whether the value of the column is actually null, not whether the column exists....?

0
 
TheAvengerCommented:
Sorry, I didn't get your question correctly. You wrote: "but how can I check that row["name"] actually exists" - I though you are trying to get if the value in the column exists.

So, to check the column:

if (table.Columns["name"] != null)
    // Do whatever
0
 
rohanpandyaCommented:
it check for the values of that column is null means it exists or not? It's work try it
0
 
WinterMuteUKAuthor Commented:
Sorry - my fault for not explaining/wording properly....
I don't have the table at this point:

public static string GetNameFromDataRow(DataRow row)
{
     return row["name"].ToString();
}

All I have is the DataRow, and I would like to do something like:

public static string GetNameFromDataRow(DataRow row)
{
     if(row.Contains("name"))
          return row["name"].ToString();
     else return null;
}

0
 
WinterMuteUKAuthor Commented:
If the value of the column is null, thats still a valid result in my system, so checking for null doesn't help in that case!
0
 
WinterMuteUKAuthor Commented:
Equally I suppose I could use:

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

Thanks a lot mate, I just didn't see that!

Wint

0
All Courses

From novice to tech pro — start learning today.