Avatar of Peter Allen
Peter Allen
Flag for United States of America asked on

Creating a temporary datatable and adding columns

Experts,

For several years I have been using the following code without issue:
        Dim dtDataTable As DataTable = New DataTable
        Dim iRow As Integer = 0
        Dim iCol As Integer = 0
        Dim dtCol() As DataColumn = Nothing
        Dim oRow As DataRow = Nothing
        For iLoop As Integer = 1 To 3
            dtCol(iLoop - 1) = New DataColumn
            dtDataTable.Columns.Add(dtCol(iLoop - 1))
        Next iLoop

Open in new window


For some reason, however, today I encountered a Null Reference exception on the line:
"dtCol(iLoop - 1) = New DataColumn"

Earlier in the code I have identified dtCol() as a DataColumn and assigned Nothing to it until I needed to.  This is really weird.

I am now using VisualStudio Community 2015 with .Net 4.6.  Am I mussing something.  I bet ots going to be really easy, but I can't see it for some reason.  Your help would be appreciated.  Thank you
Visual Basic.NET

Avatar of undefined
Last Comment
Fernando Soto

8/22/2022 - Mon
Scott McDaniel (EE MVE )

You can add Columns like this:

For iLoop As Integer = 1 To 3
  dtDataTable.Columns.Add ("Col" & (iLoop-1).ToString, GetType(String))
Next iLoop
ASKER CERTIFIED SOLUTION
Fernando Soto

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Peter Allen

ASKER
Thank you
Fernando Soto

Not a problem Peter, glad to help.
Your help has saved me hundreds of hours of internet surfing.
fblack61