wapt49 wapt49 - 1 year ago 91
Vb.net Question

Object reference not set to an instance of an object

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download