views:

1392

answers:

4

Hi,

I have a function that search for a keyword and then return DataTable. I want to check if there rows inside because sometimes there's no query found.

    'which one shoud I use ?
    If dtDataTable Is Nothing Then
        'some code
        lbl_count.Text = "Found 0 result"
    End If

    If dtDataTable.Rows.Count > 0 Then
        'some code
        lbl_count.Text = "Found " & dtDataTable.Rows.Count.ToString & " results"
    End If

Thanks.

+1  A: 

You should use the second, i dont think the first would work, and if it did the second would not work because dtDataTable.Rows would throw a null reference exception.

John Boker
Yes, it'd throw Object reference not set to an instance of an object.
Angkor Wat
+4  A: 

How about:

If dtDataTable IsNot Nothing AndAlso dtDataTable.Rows.Count > 0 Then
    'some code
    lbl_count.Text = "Found " & dtDataTable.Rows.Count.ToString & " results"
Else
    'some code
    lbl_count.Text = "Found 0 result"
End If
Steve Echols
+1  A: 

If you're using VB 9.0 (VS 2008) you can simply this with the following

lbl_count.Text = String.Format("Found {0} result(s)", if(dbDataTable, dbDataTable.Rows.Count,0))
JaredPar
A: 

Steve Echols got both the nails on their heads and just so you know the Andalso checks the first condition and if the first condition fails then a FALSE is returned; if the first condition is TRUE then and only then does it check the second condition.

this way John Boker's point is also taken care of!

Kudos to both!

thisismydisplayname