0

I'm trying to test out the new Null-Conditional operator in .NET 4.6 (using VB.Net), but it isn't working for me when retrieving null values from fields of a database record, and I can't understand why. Here's my code:

Dim dbtable As New DataSet1.MyDataTable
Dim dbrecord As DataSet1.MyRecord

dbrecord = dbtable.NewMyDataTableRow
Dim val = dbrecord.CustomerName?.ToString

Yet, it still throws a System.Data.StrongTypingException.

What am I doing wrong?

Avi
  • 962
  • 9
  • 17
  • possible duplicate of [Most efficient way to check for DBNull and then assign to a variable?](http://stackoverflow.com/questions/221582/most-efficient-way-to-check-for-dbnull-and-then-assign-to-a-variable) – Mystra007 Sep 04 '15 at 18:47

2 Answers2

1

It looks like CustomerName's value is DBNull, not null. See what the documentation on StrongTypingException says:

The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value.

The null-conditional operator can't help you with a DBNull value.

I think you have no choice but to manually check for dbrecord.IsCustomerNameNull (you should have a property named like that) before attempting to read CustomerName.

sstan
  • 35,425
  • 6
  • 48
  • 66
  • to complete @sstan answer you can check this link: http://stackoverflow.com/questions/221582/most-efficient-way-to-check-for-dbnull-and-then-assign-to-a-variable. – Juan Ruiz de Castilla Sep 04 '15 at 16:11
0

I figured out a workaround that isn't as cumbersome as always checking IsCustomerNameNull. Use this instead:

Dim val = dbrecord("CustomerName")?.ToString
Avi
  • 962
  • 9
  • 17