avoid checking for DataRow.IsDBNull on each column?

前端 未结 4 1853
无人及你
无人及你 2021-01-19 07:46

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 cod

4条回答
  •  情深已故
    2021-01-19 08:01

    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 ("").

提交回复
热议问题