我正在從一個項目中獲取數據庫中的數據。錯誤:從'DBNull'類型到'String'類型的轉換無效
現在我收到此錯誤信息:
Conversion from type 'DBNull' to type 'String' is not valid
我知道是什麼錯誤意味着,我只是需要一種方法來解決它。
我有以下代碼:
Private Function ParseSeamansNames(ByVal seaman As ItemsDataSet.SeamenRow) As String
If (seaman Is Nothing) Then Return String.Empty
Dim name As String
Dim firstNames() As String = Split(seaman.FirstName.Replace("-", " "))
Dim index1 As Integer = CInt(seaman.GivenNameNumber.Substring(0, 1))
Dim index2 As Integer = CInt(seaman.GivenNameNumber.Substring(1, 1))
If (index1 > firstNames.Length - 1) Then
index1 = 0
End If
If (index2 > firstNames.Length - 1) Then
index2 = 0
End If
If (index1 = 0 And index2 = 0) Then
name = seaman.FirstName
ElseIf (index1 > 0 And index2 = 0) Then
name = firstNames(index1 - 1)
ElseIf (index1 = 0 And index2 > 0) Then
name = firstNames(index2 - 1)
Else
name = firstNames(index1 - 1) & "-" & firstNames(index2 - 1)
End If
name = name & " " & seaman.LastName
Return name
End Function
我試圖將其更改爲If (seaman Is Nothing) Then Return DBNull
,但我得到的錯誤:
dbnull is a type and cannot be used as an expression
我真的不知道如何解決它。誰能幫我?
UPDATE:
我得到這個錯誤:
[InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.]
Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value) +715847
BUMSSeamenWebb.ItemsService.SeamenRow.get_FirstName() in C:\BUMS LOKAL\Dev\Projects\BUMSSeamenWebb\Web References\ItemsService\Reference.vb:51036
這行是該代碼:
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property FirstName() As String
Get
Try
Return CType(Me(Me.tableSeamen.FirstNameColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'FirstName' in table 'Seamen' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSeamen.FirstNameColumn) = value
End Set
End Property
特別是:
Return CType(Me(Me.tableSeamen.FirstNameColumn),String)
我看不出這裏的問題
更新2:
這是檢查其他列
Private Sub SetSeamanData(ByRef itemRow As ItemsDataSet.ItemsRow, ByVal seaman As ItemsDataSet.SeamenRow)
itemRow.PersonalIdentityNumber = seaman.PersonalIdentityNumber
itemRow.Name = ParseSeamansNames(seaman)
itemRow.CitizenShipCode = seaman.CitizenshipCode
If Not seaman.IsEmailNull() Then
itemRow.EmailAddress = seaman.Email
Else
itemRow.EmailAddress = Nothing
End If
If Not seaman.IsTelephoneNull() Then
itemRow.TelephoneNumber = seaman.Telephone
Else
itemRow.TelephoneNumber = Nothing
End If
If Not seaman.IsMobiletelephoneNull() Then
itemRow.MobilephoneNumber = seaman.Mobiletelephone
Else
itemRow.MobilephoneNumber = Nothing
End If
End Sub
@sstan謝謝,我更新了我的問題。如果你能再次檢查,我很感激。 –
'如果不是IsDBNull',那麼執行您的檢查...請記住,'DBNull'實際上與'Nothing'不一樣。 – user2366842
另外,作爲一個附註,最好檢查一下,確保你輸入INT的值實際上是數字,然後再嘗試投它們...... – user2366842