如何检查字段为null

时间:2016-04-22 18:02:56

标签: asp.net vb.net

我知道如何做到这一点,但我想知道最佳做法......

我从表中获取一行数据。其中一些字段可以为NULL。我目前正在为每个字段使用if语句,如果它不是NULL,则根据需要填充文本框或标签。

这对我来说似乎很麻烦,但我无法想出一个更好的方法来检查空值并采取相应的行动。

这有意义吗?还有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

由于vb.net 14最好的方法是使用?

  

使用Visual Basic 14,您可以优雅地处理a的可能性   像这样null,使用新的?操作者:

Console.WriteLine("{0} ({1})",
  customer.Name,
  customer.Address?.Country)

Link to vb.net article.

Link to c# article.

答案 1 :(得分:0)

如果您使用SqlDataReader处理SqlCommand,则可以检查SqlDataReader.IsDBNull属性。这是一个真实世界的例子:

    Try
        Using con = New SqlConnection(dbConnectString)
            Using cmd = New SqlCommand("usp_GetValue", con)
                cmd.Parameters.Add("@nvcKey", SqlDbType.VarChar).Size = key.Length
                cmd.Parameters("@nvcKey").Value = key
                con.Open()
                Using reader As SqlDataReader = cmd.ExecuteReader()
                    If reader.Read() Then
                        If Not reader.IsDBNull(1) Then ExpriryDateUTC = reader.GetDateTime(1)
                        AllowMemoryCache = reader.GetBoolean(2)
                        If reader.IsDBNull(0) Then
                            value = Nothing
                            Return False
                        Else
                            value = DeserializeDataContractOjectFromXML(Of T)(reader.GetString(0))
                            Return True
                        End If
                    Else
                        Return False
                    End If
                End Using
            End Using
        End Using
    Catch ex As Exception
        Return False
    End Try
相关问题