避免在每一列上检查 DataRow.IsDBNull? [英] avoid checking for DataRow.IsDBNull on each column?

查看:19
本文介绍了避免在每一列上检查 DataRow.IsDBNull?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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!

解决方案

You could simply use String.Join and pass row.ItemArray:

For Each row As DataRow In sqlDataset.Tables(0).Rows
    Response.Write(String.Join("", row.ItemArray))
Next

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 return null/Nothing for string. Then you could use the null-coalescing operator (?? in C#, If in VB).

Dim rowInfo = String.Format("{0}{1}{2}",
                            If(row.Field(Of String)("Column1"), ""),
                            If(row.Field(Of String)("Column2"), ""),
                            If(row.Field(Of String)("Column3"), ""))

However, note that String.Format will convert null/Nothing to "" implicitely anyway, so the If is redundant and just fyi.

MSDN:

If the object specified by index is a null reference (Nothing in Visual Basic), then the format item is replaced by the empty string ("").

这篇关于避免在每一列上检查 DataRow.IsDBNull?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆