syntax to check if variable is blank

I would like to check if both variables are not blank or empty
         var addtype = (Label)ri.FindControl("lblUnitType");
                    var addstreet = (Label)ri.FindControl("lblStreet");

Open in new window


I'd like to check if addtype and addstreet are not empty
zachvaldezAsked:
Who is Participating?
 
Martin MillerConnect With a Mentor CTOCommented:
you need to add logic like this
if(data != null) e.g.
// This is one level check for empty
if (addtype != NULL  &&  addstreet != NULL)

Open in new window

0
 
Dave KeeneConnect With a Mentor Commented:
Try...

if ( addtype.Trim().Length == 0 ) ....... to work out whether the label appears to be empty.  It will in all likelihood contain blanks.
0
 
Russ SuterConnect With a Mentor Commented:
Couple of points to make here.

1. There's a fundamental difference between "empty" and "null". What you need to check for is whether the variable is null. Martin Miller's example does that.
2. Unless you have a compelling reason to use the "var" keyword you should avoid it. It won't necessarily cause you any issues right now but the more of these you end up using the less maintainable your code becomes. If you know the data type ahead of time, obviously in this case you do since you're explicitly casting) you should declare the variable properly typed.
3. Consider using safe type conversion for cases where you cannot be certain that the cast will be successful or cases where a null result is possible.

With those three conditions in mind, here's how I'd rewrite what you have above.
Label addtype = ri.FindControl("lblUnitType") as Label;
if (addtype != null)
{
  // safe to do stuff
}
Label addstreet = ri.FindControl("lblStreet") as Label;
if (addstreet != null)
{
  // safe to do stuff
}

Open in new window

0
 
zachvaldezAuthor Commented:
Since I’m checking each row in the repeater, I would like to use For each...
To make sure the 2 variables are not null or empty
0
 
zachvaldezAuthor Commented:
I was able to follow Martin's solution. I thought the test for the variable as null instead of ""(blank) was the best. This type of problem commonly is faced by programmers and sometimes it takes experience to recognize it. I'm glad Ross Suter explained and reinforced the reasons behind it and even showed some codes and I appreciated that as well. He deserves credit likewise.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.