0

I have a DataRow which contain data from database. I want to check each data column for Null value in an IF condition. I found two ways to check NULL value.

 If IsDBNull(drType("ISShort")) Then
    StartDate.Visible = True
 Else
    StartDate.Visible = False
 End If

and

 If Not drType("ISShort").ToString Is DBNull.Value  Then
   StartDate.Visible = True
 Else
   StartDate.Visible = False
 End If

Both works fine for me but I don't know which one is better to use ?

Abdul
  • 2,002
  • 7
  • 31
  • 65

2 Answers2

3

I prefer DataRow.IsNull which returns a bool, is readable and efficient:

StartDate.Visible = drType.IsNull("ISShort")

related: Which of IsDBNull and IsNull should be used?

Note that your second approach doesn't work. If you convert it to String with ToString it can't be DBNull.Value. That compiles only with option-strict set to off which i strongly advise against.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks @Tim. Then what is `DBNull.Value` for. The code was previously written using `DBNull.Value` and when I debug the code, it is working fine. – Abdul Jul 11 '16 at 10:23
  • 1
    The last point is what I wrote in my comment. But @Abdul said he got the correct results with the ToString approach. How can that be? – Alex B. Jul 11 '16 at 10:23
  • The `drType("ISShort")` contains a `boolean` value. I think, I provided a complete code section to test. – Abdul Jul 11 '16 at 10:36
  • 1
    @Abdul: it works accidentially because VB tries to fix your code. It will magically convert `DbNull.Value` to a string by calling `ToString` which returns `String.Empty`. But don't do it, instead write type safe code. It wouldn't compile anyway if you'd change it to option strict on, what you should always do project-wide. – Tim Schmelter Jul 11 '16 at 10:40
  • 1
    @AlexB.: look at my last comment, it's one of the "features" of VB to fix not working code for you. I wouldn't go with the [`IsDbNull` function](https://msdn.microsoft.com/en-us/library/tckcces5(v=vs.90).aspx) because it's an old "global" VB6 function, so it's not .NET and would not compile in C# and it's less efficient. – Tim Schmelter Jul 11 '16 at 10:43
  • Thanks. I misread your answer as `IsDbNull` instead of `IsNull`. Those old VB6 compatibility functions are really a blessing ;) – Alex B. Jul 11 '16 at 13:16
1

Second case makes no sense as it does unnecessary ToString().

Note, there is another way you can use DbNull

If DbNull.Value.Equals(row.Item(fieldName)) Then
...

you can also use myDataRow.IsNull(fieldName) which is faster according to Which of IsDBNull and IsNull should be used?

Community
  • 1
  • 1
user2316116
  • 6,726
  • 1
  • 21
  • 35