1

I have already have a look at such posts like: Object Reference Errors but still cannot find the answer I am looking for.

foreach (var test in (gathered as tblbus_address).Address1)

returns this error:

System.NullReferenceException: Object reference not set to an instance of an object.


I have tried checking if it is null before:

if(!string.IsNullOrEmpty((gathered as tblbus_address).Address1){}

I have tried adding ToString(); and making sure it is !=null;


However, even after all this, I receive the same error.

Community
  • 1
  • 1
Jaquarh
  • 6,493
  • 7
  • 34
  • 86

2 Answers2

4

You are doing too many things in foreach statement. Rather split it up, this way you can neatly handle the null checks rather than getting the null reference exception.

var address = gathered as tblbus_address
if(address!=null && address.Address1 !=null)
{
  foreach (var test in address.Address1)
  {
    //do your stuff
  }
}
Carbine
  • 7,849
  • 4
  • 30
  • 54
1

This should work for you

var data=gathered;
if(data!=null && !String.IsNullOrEmpty(data.Address1))
{
foreach (var test in (data as tblbus_address).Address1)
} 
Mir Gulam Sarwar
  • 2,588
  • 2
  • 25
  • 39