我正在经历一个我有DataTable的场景,其中有多种类型的列,我必须过滤掉Null Valued Column的数据类型,这样我就可以为它分配一些默认值,现在没有任何内容陷阱。以下是测试代码。
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim table As DataTable = GetTable()
'
' We can instantiate a new object array and add it as a row.
'
Dim row As DataRow = table.Rows(1)
For Each item As Object In row.ItemArray
If TypeOf item Is Integer Then
Console.WriteLine("Int: {0}", item)
ElseIf TypeOf item Is String Then
Console.WriteLine("String: {0}", item)
ElseIf TypeOf item Is DateTime Then
Console.WriteLine("DateTime: {0}", item)
ElseIf TypeOf item Is System.DBNull Then
Console.WriteLine("DBNULL {0}", item)
End If
Next
End Sub
Private Shared Function GetTable() As DataTable
' Here we create a DataTable with four columns.
Dim table As New DataTable()
table.Columns.Add("ID", GetType(Integer))
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Desc", GetType(String))
table.Columns.Add("Date", GetType(DateTime))
' Here we add five DataRows.
table.Rows.Add(1, "Abc", "Cool Down", DateTime.Now)
table.Rows.Add(2, "Chenno", "Helifire", DBNull.Value)
Return table
End Function
结束班
我只遍历Null Valued Column Row,对于日期列,它显示" System.DBNull" 。我需要弄清楚这个列的数据类型。
答案 0 :(得分:1)
我已经找到了如何使用特定列,有两种方法 1:列名称 2:或者通过该列的索引及其DataType
Dim row As DataRow = table.Rows(1)
Dim index As Integer = 0
For Each item As Object In row.ItemArray
If TypeOf item Is Integer Then
Console.WriteLine("Int: {0}", item)
ElseIf TypeOf item Is String Then
Console.WriteLine("String: {0}", item)
ElseIf TypeOf item Is DateTime Then
Console.WriteLine("DateTime: {0}", item)
ElseIf TypeOf item Is System.DBNull Then
Console.WriteLine("DBNULL {0}", item)
End If
If table.Columns(index).ColumnName.Contains("Date") Then
'Do the stuff {Method 1}
End If
If table.Columns(index).DataType.ToString() = "System.DateTime" Then
'Do The Stuff {Method 2}
End If
index = index + 1
Next