因为INT (Int32) 的条目之一可以为空并且包含Null (DBNull)。 Null 值不会像您预期的那样返回为 Nothing,原因很简单,在 .NET 1.0 中创建它时不存在任何可为空的值类型。
我认为DataGridViewRows 没有现成的扩展方法,就像DataRows(即DataRow.Field<T>())一样,但您可以创建自己的函数,如下所示:
Public Sub Foo()
Dim DataGridView1 As DataGridView = Nothing
If e.ColumnIndex = 0 Then
Dim currentRow As DataGridViewRow = DataGridView1.CurrentRow
'UserID is a variable holding a value in database field of User_ID
publicRegistrationId = ToInt32Nullable(GetValue(currentRow, 1))
userName_txt.Text = ToString(GetValue(currentRow, 3))
adminRight_chk.Checked = ToBoolean(GetValue(currentRow, 4))
financeRight_chk.Checked = ToBoolean(GetValue(currentRow, 5))
operationRight_chk.Checked = ToBoolean(GetValue(currentRow, 6))
salesRight_chk.Checked = ToBoolean(GetValue(currentRow, 7))
ministry_txt.Text = ToString(GetValue(currentRow, "ministry"))
End If
End Sub
Private Shared Function GetValue(row As DataGridViewRow, columnIndex As Int32) As Object
Dim result As Object = row.Cells(columnIndex).Value
If (TypeOf result Is DBNull) Then Return Nothing
Return result
End Function
Private Shared Function GetValue(row As DataGridViewRow, columnIndex As String) As Object
Dim result As Object = row.Cells(columnIndex).Value
If (TypeOf result Is DBNull) Then Return Nothing
Return result
End Function
Private Shared Function ToInt32Nullable(value As Object) As Int32?
If (value Is Nothing) Then Return Nothing
If (TypeOf value Is Int32) Then Return CInt(value)
Dim stringValue As String = value.ToString()
Dim result As Int32
If (Int32.TryParse(stringValue, NumberStyles.Number, CultureInfo.InvariantCulture, result)) Then
Return result
End If
Throw New InvalidCastException($"Value '{stringValue}' cannot be cast into an {NameOf(Int32)}!")
End Function
Private Shared Shadows Function ToString(value As Object) As String
If (value Is Nothing) Then Return Nothing
If (TypeOf value Is String) Then Return CStr(value).Trim()
Return value.ToString()
End Function
Private Shared Function ToBoolean(value As Object) As Boolean
If (value Is Nothing) Then Return False
If (TypeOf value Is Boolean) Then
Return CType(value, Boolean)
End If
Dim stringValue As String = value.ToString().Trim()
Dim stringValueLC As String = stringValue.ToLowerInvariant()
Select Case stringValueLC
Case "", "0", "false", "off", "no", "disabled", "denied"
Return False
Case "1", "true", "on", "yes", "enabled", "granted"
Return True
End Select
Throw New InvalidCastException($"Value '{stringValue}' cannot be cast into a {NameOf(System.Boolean)}!")
End Function