-2

I know how to do this, but am wondering about best practices...

I go get a row of data from a table. Some of these fields can be NULL. I am currently using an if statement for each field and if it is NOT NULL, populate text boxes or labels as appropriate.

This seems cumbersome to me, but I couldn't think of a better method to check for nulls and act accordingly.

Does this make sense? Is there a better way?

STS1SS
  • 229
  • 1
  • 3
  • 13

2 Answers2

0

Since vb.net 14 best way is to use ?

With Visual Basic 14 you can elegantly handle the possibility of a null like this, using the new ?. operator:

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

Link to vb.net article.

Link to c# article.

Claudius
  • 1,883
  • 2
  • 21
  • 34
0

If you are using a SqlDataReader to process a SqlCommand, then you can inspect the SqlDataReader.IsDBNull property. Here's a real world example:

    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
JerryM
  • 910
  • 6
  • 9