2014-10-10 2 views
1

DataTable이 있고 그 안에 여러 유형의 열이있는 시나리오를 진행 중입니다. 일부 기본값을 할당 할 수 있도록 널 값 열의 데이터 유형을 필터링해야합니다. 여기에는 함정이 없습니다. 아래는 테스트 코드입니다.NULL에 대한 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 

나는 단지 널 소중한 열 행을 통과하고

최종 클래스, 날짜 열을 위해 그것은 "System.DBNull"를 보여줍니다. 이 열의 데이터 유형을 알아 내야합니다. 열 이름 2 :

답변

1

가 나는 두 가지 방법 1, 특정 열로 작업하는 방법을 알아 낸 또는 그 컬럼의 인덱스와 데이터 형식으로

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