是否存在DataCell类

时间:2018-12-06 15:47:21

标签: vb.net datatable

我有几个实用程序功能可测试“空单元格”(定义为NULL为空的String值)。一个用于DataGridViewCell,另一个用于DataTable单元格。通常,这些方法似乎已经足够好用,但是我目前必须通过传递所讨论的特定单元格的DataTable的行和列ID来调用测试DataTable单元格的方法,而测试空DataGridViewCell的方法只需要特定的对象进行测试。

Public Shared Function IsCellEmpty(ByVal Cell As DataGridViewCell) As Boolean
    If Cell.Value Is Nothing OrElse Cell.Value Is DBNull.Value OrElse String.IsNullOrEmpty(Cell.Value.ToString) Then
        Return True
    Else
        Return False
    End If
End Function

Public Shared Function IsCellEmpty(ByVal Row As DataRow, ByVal ColumnIndex As Integer) As Boolean
    If Row(ColumnIndex) Is DBNull.Value OrElse String.IsNullOrEmpty(Row(ColumnIndex).ToString.Trim) Then
        Return True
    Else
        Return False
    End If
End Function

Public Shared Function IsCellEmpty(ByVal Row As DataRow, ByVal ColumnName As String) As Boolean
    If Row(ColumnName) Is DBNull.Value OrElse String.IsNullOrEmpty(Row(ColumnName).ToString.Trim) Then
        Return True
    Else
        Return False
    End If
End Function

' *** USAGE EXAMPLE ***
For Each CurrentRow As DataRow In MyDataTable.Rows
    If Not Utility.IsCellEmpty(CurrentRow, "CellName") Then
        ' Do Something Here...
    End If

    If Not Utility.IsCellEmpty(CurrentRow, 5) Then
        ' Do Something Here...
    End If
Next CurrentRow

' *** WHAT I'D LIKE TO SEE ***
For Each CurrentRow2 As DataRow In MyDataTable.Rows
    If Not Utility.IsCellEmpty(CurrentRow("CellName")) Then
        ' Do Something Here...
    End If

    If Not Utility.IsCellEmpty(CurrentRow(5)) Then
        ' Do Something Here...
    End If

    ' *** OR ***
    For Each CurrentCell As DataCell In CurrentRow.Cells
        If Utility.IsCellEmpty(CurrentCell) Then
            ' Do Something Here...
        End If
    Next CurrentCell
Next CurrentRow2

因此,为了使标题中的问题更加具体,是否将DataCell类作为DataTable的一部分,可以类似于DataGridViewCell类进行引用?显然,这是个人喜好而不是实际的需求问题,但是我想我要问的是其他人有同样的问题。在搜索中,我一直无法找到这个特定的对象类,但是我敢肯定,这里的人至少可以将我指向正确的方向。

1 个答案:

答案 0 :(得分:1)

否,没有像DataCell这样的东西。有一个DataColumn,但这只是存储诸如名称和类型之类的列信息,而不是存储表中某一行中的值。

DataRow存储所有字段,因此您可以像过去那样传递它。与其将winforms类型传递给此方法,不应该提供一种不依赖于特定框架的方法(DBNull与winforms无关)。相反,您应该提供一个采用Object的方法。然后,您可以将其用于DataGridViewCellDataRow字段。

Public Shared Function IsValueNullOrEmpty(ByVal value As Object) As Boolean
    Return value Is DBNull.Value OrElse String.IsNullOrEmpty(value?.ToString()) 
End Function

Public Shared Function IsCellValueNullOrEmpty(ByVal cell As DataGridViewCell) As Boolean
    Return IsValueNullOrEmpty(cell?.Value?.ToString())
End Function

Public Shared Function IsFieldNullOrEmpty(ByVal row As DataRow, ByVal columnIndex As Integer) As Boolean
    Return IsValueNullOrEmpty(row?(columnIndex))
End Function

Public Shared Function IsFieldNullOrEmpty(ByVal row As DataRow, ByVal columnName As String) As Boolean
    Return IsValueNullOrEmpty(row?(columnName))
End Function