DataRow: Check for empty (Not "null) fields in DataSet

15,415

Solution 1

you can use stirng.isNullorEmpty to check for empty fields. String.isNullorEmpty

if (Particle.Tables.Count == 0 || string.isNullorEmpty(pDr.ItemArray[1].ToString()))
{
   tblParticle.Append("No Data");
} 

.

Solution 2

if (string.IsNullOrEmpty(pDr.ItemArray[1].ToString()))
{
  tblParticle.Append("No Data");
}
else
{
  //else do something else
}

checking for NULL will not hurt keep in mind that Null and Empty are two different things

Solution 3

The following assumes we are talking about a string (VARCHAR/CHAR) column:

  • If you don't care if it is null or an empty string, and always want an empty string back, you can use DataRow["name"].ToString()
  • If you want your string object to become null or empty just like the field value, you can use DataRow["name"] as string
  • If you want to get an exception in case of NULL, you can use (string) DataRow["name"]
Share:
15,415
John Kinane
Author by

John Kinane

Just a guy making his way in the world

Updated on June 04, 2022

Comments

  • John Kinane
    John Kinane almost 2 years

    Hopefully this is an easy one. Is there a way to test for an "empty" field using DataRow? The following work fine for testing against a field with null values, unfortunately, the column I'm dealing with are either populated with data or are just "empty". Is there an approach in C# I'm missing? Thanks

    if (Particle.Tables.Count == 0 || pDr.ItemArray[1].ToString() == "")
    tblParticle.Append("No Data");
    
  • gabsferreira
    gabsferreira over 12 years
    Didn't you forget the "string." before the IsNullOrEmpty method?
  • MethodMan
    MethodMan over 12 years
    yes sorry about that.. I was typing faster than I was thinking.. thanks devGabriel
  • MethodMan
    MethodMan over 12 years
    I would suggest wrapping the if statement in a code block { } in the event that he may need to do something different later down the road..
  • John Kinane
    John Kinane over 12 years
    At the moment, although this all helps, it's still not working for me. No explanation as to why. I can see the fields are empty in the database that I'm testing against to technically this "should" work? If I test this and what I had to start with and change the array position to column with known "nulls" it works.