-2

I got an error on this line that said "Object reference not set to an instance of an object"

Me.ShipTextValue.Text = IIf(String.IsNullOrWhiteSpace(orderHeader.ShippingText), String.Empty, orderHeader.ShippingText.Replace(Environment.NewLine, "<br />"))

However I don't think there is an error on that line, can anyone help me to see whether any error on that line?

Many Thanks

wapt49
  • 213
  • 2
  • 16
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – A Friend Nov 15 '16 at 09:25
  • Try `If` rather than `IIf`. Look at [this](http://stackoverflow.com/questions/28377/performance-difference-between-iif-and-if) for more information on the difference. – Bugs Nov 15 '16 at 09:25

1 Answers1

4

Don't use the old VB6 IIF function but the If-operator, it uses short-circuit evaluation as opposed to IIF which evaulates both expressions even if the first already was True.

That causes the NullReferencexception if orderHeader.ShippingText is Nothing.

Me.ShipTextValue.Text = If(String.IsNullOrWhiteSpace(orderHeader.ShippingText), String.Empty, orderHeader.ShippingText.Replace(Environment.NewLine, "<br />"))

If you use Visual Basic 14 you can use the null propagation operator:

ShipTextValue.Text = orderHeader.ShippingText?.Replace(Environment.NewLine, "<br />")

This will also return "" if orderHeader.ShippingText is Nothing.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939