vb.net 检查DataTable是否有行的有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/851075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:13:01  来源:igfitidea点击:

Efficient way to check if DataTable has row

vb.netdatatable

提问by Angkor Wat

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.

我有一个搜索关键字然后返回 DataTable 的函数。我想检查里面是否有行,因为有时找不到查询。

    '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.

谢谢。

回答by Steve Echols

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

回答by JaredPar

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

如果您使用的是 VB 9.0 (VS 2008),您可以简单地使用以下命令

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

回答by thisismydisplayname

Steve Echols got both the nails on their heads and just so you know the Andalsochecks 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.

Steve Echols 把两个钉子都钉在了他们的头上,所以你知道Andalso检查第一个条件,如果第一个条件失败,则返回 FALSE;如果第一个条件为 TRUE,那么它才会检查第二个条件。

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

这样约翰·博克的观点也得到了照顾!

Kudos to both!

为两人点赞!

回答by John Boker

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.

你应该使用第二个,我不认为第一个会起作用,如果它起作用,第二个将不起作用,因为 dtDataTable.Rows 会抛出一个空引用异常。