DareDevil
DareDevil

Reputation: 5349

DataRow ArrayItem's DataType for NULL Values vb.net

I am undergoing a scenario where I have DataTable and there are multiple types of columns in it, I have to filter out the Data Type of Null Valued Column so i can assign some default value to it, right now there is nothing to trap. Below is the Code for Testing.

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

End Class

I am traversing only the Null Valued Column Row, For date Column it shows "System.DBNull" . i need to figure out this column's datatype.

Upvotes: 1

Views: 2871

Answers (1)

DareDevil
DareDevil

Reputation: 5349

I have figured out how to work with specific column, with two ways 1: Column Name 2: Or by the index of That column and its 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

Upvotes: 1

Related Questions