Tola
Tola

Reputation: 2421

Efficient way to check if DataTable has row

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.

Upvotes: 9

Views: 66112

Answers (4)

thisismydisplayname
thisismydisplayname

Reputation: 31

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!

Upvotes: 1

JaredPar
JaredPar

Reputation: 755179

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))

Upvotes: 3

Steve Echols
Steve Echols

Reputation: 409

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

Upvotes: 27

John Boker
John Boker

Reputation: 83719

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.

Upvotes: 1

Related Questions