Building a DataTable in a For loop


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Building a DataTable in a For loop

  1. #1
    Join Date
    Apr 2005
    Posts
    1

    Building a DataTable in a For loop

    Code:
    Dim dt As DataTable
    Dim i As Int32
    For i = 0 To sentDT.Columns.Count - 1
        dt.Columns.Add(sentDT.Columns(i).Caption, sentDT.Columns(i).DataType)
    Next
    sentDT is a DataTable passed in to a function. It has data in it. The code compiles, but when I run it I get this error:

    Object reference not set to an instance of an object.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    The error occurs on the dt.columns.add line.

    What I am trying to do here is create a copy of sentDT columns, without having to write it all out by hand, since there are a good number of columns in this table.

  2. #2
    Join Date
    Aug 2004
    Posts
    64
    You variable dt is not set to an instance of an object. Dim dt As DataTable creates a null DataTable reference. You still have to create the DataTable object.

    Do this instead:
    Dim dt As New DataTable

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center