My code is 2x longer than it would be if I could automatically set IsDBNull
to ""
or simply roll over it without an error.
This is my code:
Dim conn As New SqlConnection
conn.ConnectionString = Module1.DBConn2
Dim sqlCommand = New SqlCommand("SELECT * FROM table", conn)
conn.Open()
Dim sqlDataset As DataSet = New DataSet()
Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
sqlDataAdapter.Fill(sqlDataset)
conn.Close()
For Each rs As DataRow In sqlDataset.Tables(0).Rows
If Not IsDBNull(rs("column")) Then
Response.Write(rs("column"))
Else
Response.Write("")
End If
Response.Write("some stuff to write")
If Not IsDBNull(rs("column2")) Then
Response.Write(rs("column2"))
Else
Response.Write("")
End If
Next
In that case I'd just like to type Response.Write(rs("column"))
instead of the If
statement, and if column
IsDBNull
then output an empty string.
How can I do this?
Many thanks in advance!
Ceres's answer is probably the best given that it avoids any sort of null testing, but it's worth noting that the 'IIF' function would also work pretty well her. It's still going to do the test for null but it's much more compact than how Joe was originally doing it. Something like this should do the trick:
What's neat with this is you can substitute the "" for whatever you want to output if the value is in fact null ( a nice little added bonus. )
Here's some info on the 'IIF' function for those who don't know what it is:
http://msdn.microsoft.com/en-ca/library/27ydhh0d(v=vs.71).aspx
Dataset Extensions give you a clean way of doing and it's also strongly typed. The type must match the column type in the database though. If the database column can be null, then use a nullable type like below. The null values become Nothing for the returned nullable type.
Here's a one-liner:
or make it an extension method:
then call it as:
You could simply use
String.Join
and passrow.ItemArray
:That works since
DBNull.ToString
returns an empty string.If you want to address every column, you can use the strongly typed
DataRowExtensions.Field
method which supports nullables and returnnull
/Nothing
for string. Then you could use thenull-coalescing operator
(??
in C#,If
in VB).However, note that
String.Format
will convertnull
/Nothing
to""
implicitely anyway, so theIf
is redundant and just fyi.MSDN: