在将数据从数据库填充到datagridview时,我需要一种将DBNull转换为字符串的方法。以下是我的代码
Private Sub FetchData()
sql = "SELECT ContributionType,Status,PayMethod,BankName,AccountNo,Amount,FullName,District,Refno,ContributorGrp"
sql &= " FROM tblincome WHERE TxnID=@id"
command = New OleDbCommand(sql, connection)
command.Parameters.Add(New OleDbParameter("@id", OleDbType.VarChar)).Value = lbltxnid.Text
adapter = New OleDbDataAdapter(command)
dt = New DataTable
adapter.Fill(dt)
For Each row In dt.Rows
PopulateGrid(row(0), row(1), row(2), row(3), row(4), row(5), row(6), row(7), row(8), row(9))
Next
dt.Rows.Clear()
dt.Dispose()
End Sub
Private Sub PopulateGrid(ContributionType As String, Status As String, PayMethod As String, BankName As String _
, AccountNo As String, Amount As Double, FullName As String, District As String _
, Refno As String, ContributorGrp As String)
Dim row As String() = New String() {ContributionType, Status, PayMethod, BankName, AccountNo, Amount.ToString("N") _
, FullName, District, Refno, ContributorGrp}
dgvcontributions.Rows.Add(row)
End Sub
BankName和Accountno字段允许空条目,因此它们最有可能是具有空值的条目。
答案 0 :(得分:0)
您可以使用此方法:
Public Shared Function ConvertDbVal(Of T)(obj As Object, Optional nullFallbackVal As T = Nothing) As T
If obj Is Nothing OrElse obj.Equals(DBNull.Value) Then
Return nullFallbackVal
Else
Return CType(obj, T)
End If
End Function
用法:
Dim bankName As String = ConvertDbVal(row(3), "")
Dim accNumber = ConvertDbVal(row(4), "")
如果您没有指定(可选)后备值,则必须明确指定类型:
Dim bankName As String = ConvertDbVal(Of String)(row(3))