【发布时间】:2023-03-07 23:03:04
【问题描述】:
我正在从事一个从数据库获取数据的项目。
现在我收到此错误消息:
从“DBNull”类型到“String”类型的转换无效
我知道错误的含义,我只需要一种方法来修复它。
我有以下代码:
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 是一种类型,不能用作表达式
我真的不知道如何解决它。谁能帮我?
更新:
我收到此错误:
[InvalidCastException:从“DBNull”类型转换为“String”类型 无效。]
Microsoft.VisualBasic.CompilerServices.Conversions.ToString(对象 价值)+715847
C:\BUMS 中的 BUMSSeamenWebb.ItemsService.SeamenRow.get_FirstName() 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 谢谢,我更新了我的问题。如果您能再次检查,我将不胜感激。
-
If Not IsDBNull然后执行检查...请记住DBNull实际上与Nothing不同 -
另外作为旁注,在尝试转换它们之前检查以确保您转换为 INT 的值实际上是数字可能会很好......
-
DataRow类型有扩展方法.Field(Of T),可用于String,无需检查null。如果值为DBNull,则返回Nothing
标签: vb.net