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
- See DataRow.IsNull method - it accepts a column name or index and returns whether it is NULL
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"]
Comments
-
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 over 12 yearsDidn't you forget the "string." before the IsNullOrEmpty method?
-
MethodMan over 12 yearsyes sorry about that.. I was typing faster than I was thinking.. thanks devGabriel
-
MethodMan over 12 yearsI 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 over 12 yearsAt 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.