vb.net 使用 IIF 和 IF ELSE 时验证 String.IsNullOrEmpty VS IsDBNull

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33093107/
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-17 19:30:34  来源:igfitidea点击:

String.IsNullOrEmpty VS IsDBNull in validation when using IIF and IF ELSE

sqlvb.netif-statementnulliif

提问by japzdivino

This is not clear to me, so if anyone can explain in detailed if what is the difference of the two functions (IsDBNulland String.IsNullOrEmpty) of VB.Net.

这对我来说不清楚,所以如果有人能详细解释一下VB.Net的两个函数(IsDBNullString.IsNullOrEmpty)有什么区别。

Below is my scenario why i ask that, i have column Companyin my table which the value is NULL, then i used IIFfunction of vb.net to validate if it is NULLthen assign empty string (""), else assign the value coming from data table

下面是我为什么这么问的场景Company,我的表中有列的值是NULL,然后我使用IIFvb.net 的函数来验证它是否NULL分配空字符串(“”),否则分配来自数据表的值

Scenario:

设想:

  1. Below is using String.IsNullOrEmptyand i get a conversion error:

    Conversion from type 'DBNULL' to 'String' is not valid.

    txtCompany.Text = IIf(String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))
    
  2. However when i replace String.IsNullOrEmpty by IsDBNull, the validation works fine.

    txtCompany.Text = IIf(IsDBNull(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))
    
  1. 下面是使用String.IsNullOrEmpty并且我得到一个转换错误:

    从类型“DBNULL”到“字符串”的转换无效。

    txtCompany.Text = IIf(String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))
    
  2. 但是,当我用IsDBNull替换 String.IsNullOrEmpty 时,验证工作正常。

    txtCompany.Text = IIf(IsDBNull(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))
    

EDIT:

编辑:

And it is confusing because if i did the validation using IF ELSEcondition (see sample code below) with the use of String.IsNullOrEmpty, it works fine.

这令人困惑,因为如果我IF ELSE使用 String.IsNullOrEmpty使用条件进行验证(请参阅下面的示例代码),它可以正常工作。

    If String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString) = True Then
        txtCompany.Text = ""
    Else
        txtCompany.Text = dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString
    End If

The confusing part is when i used IIF(String.IsNullOrEmpty...etc)it returns an error. but when i used the normal IF String.IsNullOrEmpty(dtSample.Rows....etc) = Trueit works fine.

令人困惑的部分是当我使用IIF(String.IsNullOrEmpty...etc)它时会返回错误。但是当我使用正常时IF String.IsNullOrEmpty(dtSample.Rows....etc) = True它工作正常。

Any explanation would much appreciated. Thanks

任何解释将不胜感激。谢谢

回答by haraman

TL;DR

TL; 博士

  • String.IsNullOrEmpty()checks only for Empty ([blank]i.e. ''or "") or Nullvalues it does notcheck DBNull, if any field coming from database has its value DBNull it will raise an error.
  • IsDBNull()checks for DBNull(it is not same as Null)
  • .ToStringwill convert DBNullto Empty String i.e. ''
  • String.IsNullOrEmpty()只为空(支票[blank]''"")或Null值它检查DBNull,如果从数据库未来的任何领域都有其价值的DBNull它会引发错误。
  • IsDBNull()检查DBNull(与 不同Null
  • .ToString将转换DBNull为空字符串即''

Details
Consider following SQL table example (using SQL Server as base)

详细信息
考虑以下 SQL 表示例(使用 SQL Server 作为基础)

Table Structure:

表结构:

Column_Name        Type and Size   Other Properties
----------------   -------------   ----------------------
Company_ID         int             IDENTITY(1,1) NOT NULL
Company_Name       nvarchar (50)                 NOT NULL   
Company_Address    nvarchar (50)                     NULL

INSERT statements:

插入语句:

INSERT [tbl_company] ([Company_Name], [Company_Address]) VALUES ('ABC', 'QWERT')
INSERT [tbl_company] ([Company_Name], [Company_Address]) VALUES ('ASD', ' ')
INSERT [tbl_company] ([Company_Name], [Company_Address]) VALUES ('XYZ', '')
INSERT [tbl_company] ([Company_Name])                    VALUES ('PQR')

Table Data:

表数据:

Company_ID    Company_Name      Company_Address
-----------   ----------------  ---------------
1             ABC               QWERT
2             ASD               [SPACE]
3             XYZ               [BLANK]
4             PQR               NULL

Testing Company_Address with IsNullOrEmpty() and IsDBNull() using a SqlDataReader (r):

使用 SqlDataReader (r) 使用 IsNullOrEmpty() 和 IsDBNull() 测试 Company_Address:

Company_ID IsNullOrEmpty(r("Company_Address")) IsDBNull(r("Company_Address"))
---------- ----------------------------------- ------------------------------
1          False                               False
2          False                               False
3          True                                False
4          ERROR                               True

And now specific to the Question
What the OP is trying here, lets consider all statements one by one

现在具体到
OP 在这里尝试什么问题,让我们一一考虑所有陈述

The IIF statement with IsNullOrEmpty (wrong)

带有 IsNullOrEmpty 的 IIF 语句(错误

txtCompany.Text = IIf(String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))

In this statement OP is accessing the value as dtSample.Rows(grdInfo.SelectedIndex).Item("Company")and checking it with IsNullOrEmpty()and then converting the result of IsNullOrEmpty to string using .ToStringi.e. IsNullOrEmpty(value).ToString(). If the value is DBNull it will always return an error. The correct way to use it is

在此语句中,OP 访问值 asdtSample.Rows(grdInfo.SelectedIndex).Item("Company")并检查它,IsNullOrEmpty()然后使用.ToStringie将 IsNullOrEmpty 的结果转换为字符串IsNullOrEmpty(value).ToString()。如果值为 DBNull,它将始终返回错误。正确的使用方法是

IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString)

See last part Company")).ToStringvs Company").ToString), just a case of MISPLACED ")"

见最后一部分Company")).ToStringvs Company").ToString),只是一个错误的情况“)”

Second (IIF with IsDBNull) and third (IF with IsNullOrEmpty) statements of OP are correct

OP 的第二个(带有 IsDBNull 的 IIF)和第三个(带有 IsNullOrEmpty 的 IF)语句是正确的

txtCompany.Text = IIf(IsDBNull(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))

If String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString) = True Then
    txtCompany.Text = ""
Else
    txtCompany.Text = dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString
End If

As regards to the second statement OP is correctly ordering the parameters i.e. first Companyfield is converted to string using dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString. This converts any DBNull to Empty string and then it checked for IsNullOrEmpty. Now as the value has already been converted to EmptyString it will not give any error.

关于第二个语句 OP 正确排序参数,即第一个Company字段使用dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString. 这会将任何 DBNull 转换为空字符串,然后检查IsNullOrEmpty. 现在,由于该值已转换为 EmptyString,因此不会出现任何错误。

Old discussions with OP

与 OP 的旧讨论

The difference is clear in your text. Your first statement is:

区别在您的文字中很明显。你的第一句话是:

txtCompany.Text = IIf(String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSpecifierRebate.Rows(grdInfo.SelectedIndex).Item("Company"))

and the second one is

第二个是

If String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString) = True Then

Now break them apart, first statement (IIF)

现在把它们分开,第一个声明(IIF)

String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString
'Item("Company")).ToString

And second part (IF)

第二部分(IF)

String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company").ToString)
'Item("Company").ToString)

Found any difference?
In first statement you are converting the result of IsNullOrEmptyto String
In second one you are converting .Item("Company") ToStringand then comparing it.

发现有什么不同吗?
在第一个语句中,您将 IsNullOrEmpty 的结果转换为 String
在第二个语句中您正在转换 .Item("Company") ToString然后进行比较。

If .Item("Company")returns DBNull
then IsNullOrEmpty failed because .Item("Company") returned type DBNullwhereas IsNullOrEmpty checks for null
IsDBNull worked because it checks for DBNull

如果.Item("Company")返回 DBNull,
则 IsNullOrEmpty 失败,因为 .Item("Company") 返回类型DBNull而 IsNullOrEmpty 检查null
IsDBNull 工作,因为它检查DBNull

All point of a misplaced bracket ")"It's a typo

错位括号的所有点“)”这是一个错字

And regarding your usage of these statements:
If and IIF need to check the results as booleans and not as strings
It is better recommended to remove the ToString portion of your statements

关于您对这些语句的使用:
If 和 IIF 需要将结果检查为布尔值而不是字符串
最好建议删除语句的 ToString 部分

回答by ??ssa P?ngj?rdenlarp

You cannot mix and match String.IsNullOrEmptyand IsDBNullbecause they work on two different things. The first on strings, the second on Data items read from the database.

你不能混合搭配String.IsNullOrEmptyIsDBNull因为它们在两种不同的东西上起作用。第一个在字符串上,第二个在从数据库读取的数据项上。

But a very important element of this is that your code is invalid. Neither "Scenario" snippet compiles under Option Strict. If you leave VB to guess what you mean, you will get confusing results.

但其中一个非常重要的因素是您的代码无效。“场景”片段都不会在Option Strict. 如果你让 VB 去猜测你的意思,你会得到令人困惑的结果。

Snippet 1:

片段 1:

txtCompany.Text = IIf(String.IsNullOrEmpty(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))

Simplified:

简化:

Dim foo = IIf(String.IsNullOrEmpty(zDT.Rows(23).Item("Name")).ToString,
                "", zDT.Rows(23).Item("Name"))

This is illegal because zDT.Rows(23).Item("Name")is an object, but String.IsNullOrEmptyexpects a string. Your ToStringis misplaced - it is not converting the db Item, it is converting the entire IIFbool expresion!

这是非法的,因为它zDT.Rows(23).Item("Name")是一个对象,但String.IsNullOrEmpty需要一个字符串。您ToString放错了位置 - 它没有转换 db Item,它正在转换整个IIFbool 表达式!

The compiler warns you of both withOption Strict On.

编译器会用Option Strict On.

The conversion throws an exception because VB must convert the db Objectitem ( zDT.Rows(23).Item("Name")) to a string. The way it does it results in an error when when the db data is DBNull.

转换会引发异常,因为 VB 必须将 dbObject项 ( zDT.Rows(23).Item("Name")) 转换为字符串。当 db 数据为 DBNull 时,它的执行方式会导致错误。

Snippet 2:

片段 2:

txtCompany.Text = IIf(IsDBNull(dtSample.Rows(grdInfo.SelectedIndex).Item("Company")).ToString, "", dtSample.Rows(grdInfo.SelectedIndex).Item("Company"))

Simplified:

简化:

foo = IIf(IsDBNull(zDT.Rows(23).Item("Name")).ToString, 
               "", zDT.Rows(23).Item("Name"))

This is slightly better but a string is till being used in place of the Boolean expression. When fixed, you have:

这稍微好一点,但直到使用字符串来代替布尔表达式。修复后,您将拥有:

IsDBNull(zDT.Rows(23).Item("Name"))

IsDBNull is testing a database item (Object) to see if it has data. It will work. IsNullOrEmptyshould not be used to test for DBNull and cant with Option Strict. You'd have to convert the dbItem to string first, then it will only work depending on how you convert.

IsDBNull 正在测试一个数据库项(对象)以查看它是否有数据。它会起作用。 IsNullOrEmpty不应该用于测试 DBNull 并且不能使用Option Strict. 您必须首先将 dbItem 转换为字符串,然后它只能根据您的转换方式工作。

' cant use string method to test an object
String.IsNullOrEmpty(zDT.Rows(23).Item("Name"))

' this will work:
String.IsNullOrEmpty(zDT.Rows(23).Item("Name").ToString)

' this will not:
String.IsNullOrEmpty(CStr(zDT.Rows(23).Item("Name")))

Use DBNull tests for data objects, and IsNullOrEmptyon strings.

对数据对象和IsNullOrEmpty字符串使用 DBNull 测试。

Also, if you use the newer Ifoperator in place of the old IIffunction you can avoid other issues. The operator allows short circuiting, the syntax is the same:

此外,如果您使用较新的If运算符代替旧IIf函数,则可以避免其他问题。运算符允许短路,语法相同:

Dim foo = If(bool expr, True result, False result)

回答by N0Alias

The IsNullOrEmptyfunction checks whether or not a string is empty or null. DBNullis not null (Nothing), but rather is a class that indicates a value from a database does not exist. IsDbNullchecks for whether or not a value equals DBNull.

IsNullOrEmpty功能,检查是否字符串为空或空。 DBNull不是 null (Nothing),而是一个指示数据库中的值不存在的类。 IsDbNull检查某个值是否等于 DBNull。

You may not be getting the error you mention in the question on the line of code referenced as this runs just fine for me:

您可能没有收到您在引用的代码行的问题中提到的错误,因为这对我来说运行得很好:

        strTest = IIf(String.IsNullOrEmpty(DBNull.Value.ToString), "", DBNull.Value)

回答by Jayanti Lal

IsDBNull Function :

IsDBNull 函数:

Returns a Boolean value that indicates whether an expression evaluates to the System.DBNull class.

返回一个布尔值,该值指示表达式的计算结果是否为 System.DBNull 类。

IsDBNull returns True if the data type of Expression evaluates to the DBNull type; otherwise, IsDBNull returns False. The System.DBNull value indicates that the Object represents missing or nonexistent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized. DBNull is also not the same as a zero-length string (""), which is sometimes referred to as a null string.

如果 Expression 的数据类型计算为 DBNull 类型,则 IsDBNull 返回 True;否则,IsDBNull 返回 False。System.DBNull 值指示对象表示丢失或不存在的数据。DBNull 与 Nothing 不同,它表示变量尚未初始化。DBNull 也与零长度字符串 ("") 不同,后者有时称为空字符串。

example :

例子 :

 Dim testVar As Object 
   Dim nullCheck As Boolean
      nullCheck = IsDBNull(testVar)
     testVar = ""
     nullCheck = IsDBNull(testVar)
     testVar = System.DBNull.Value
    nullCheck = IsDBNull(testVar)
     '  The first two calls to IsDBNull return False; the third returns True..

String.IsNullOrEmpty :

String.IsNullOrEmpty :

Indicates whether the specified string is null or an Empty string. IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is Empty.

指示指定的字符串是空字符串还是空字符串。IsNullOrEmpty 是一种方便的方法,可让您同时测试 String 是否为 null 或其值是否为 Empty。

Example :

例子 :

    Class Sample
   Public Shared Sub Main()
  Dim s1 As String = "abcd"
  Dim s2 As String = ""
  Dim s3 As String = Nothing

  Console.WriteLine("String s1 {0}.", Test(s1))
  Console.WriteLine("String s2 {0}.", Test(s2))
  Console.WriteLine("String s3 {0}.", Test(s3))
   End Sub

   Public Shared Function Test(s As String) As String
     If String.IsNullOrEmpty(s) Then
     Return "is null or empty"
    Else
     Return String.Format("(""{0}"") is neither null nor empty", s)
    End If
   End Function 
 End Class  
     'The example displays the following output:
    'String s1 ("abcd") is neither null nor empty.
     'String s2 is null or empty.
      'String s3 is null or empty.