2014-10-10 46 views
1

我正在經歷一個場景,其中有DataTable,並有多種類型的列,我必須篩選空值列的數據類型,所以我可以分配一些默認值到現在爲止,沒有什麼可以陷入。以下是測試代碼。DataRow ArrayItem的空值數據類型vb.net

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的列行,對於日期欄顯示「System.DBNull」。我需要弄清楚這個列的數據類型。

回答

1

我已想出如何與特定列工作,有兩種方式 1:列名 2:或者由列的索引和它的數據類型

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