Would like to add column to existing Datatable, then add items to it one at a time.

Posted on 2004-11-30
Last Modified: 2008-03-17
I'm quite sure this isn't the correct way to do this, but I'm also equally sure I have little to no idea what I'm talking about.
Either way, here goes.

I have an existing Datatable which contains data similar to:

COL1        COL2        COL3
Name1     Num1       Num2
Name2     Num1       Num2
Name3     Num1       Num2

I would like to add another column, and then add values to that column.
For example, after one pass in a for/next loop, the datatable would be:

COL1        COL2        COL3        COL4
Name1     Num1       Num2       Num3
Name2     Num1       Num2
Name3     Num1       Num2

After the second pass in the loop, the datatable would be:

COL1        COL2        COL3        COL4
Name1     Num1       Num2       Num3
Name2     Num1       Num2       Num3
Name3     Num1       Num2

I hope that makes sense.
Can I add a column to a datatable and then add items one at a time?

Here's what I have (which doesn't work of course):


... and then later, in a for/next loop I have:

Row = myDataTable.Rows(RowNum)
Row.Item("myColumn") = NumX

Thanks for help with my question!
Question by:DallasWebCenter
    LVL 1

    Expert Comment


    I hope i'm understanding you problem. You can add extra columns after your first pass and then just go and update that column for the first or second or whatever row.
    So if you want to update COL4 for the first row during the second pass you would say
    myDataTable.Rows.Item(0).Item(3) = "Num3"
    LVL 25

    Expert Comment

    Hi DallasWebCenter, I don't see anything wrong with it, what doesn't work what error do you get.
    how did you define Row?
    LVL 24

    Expert Comment

    by:Jeff Certain
    Is myColumn created correctly?

    Also, you can loop a little more elegantly:
    dim row as datarow
    for each row in myDataTable.Rows
      Row.Item("myColumn") = NumX
    Next row

    If the new column is calculated based on other columns, you can also do something like this to create the new column without haveing to loop through the rows at all:
    workTable.Columns.Add("SalesTax", Type.GetType("System.Double"), "Total * 0.086")

    Author Comment

    Currently, when run (without implementing any of the changes suggested here), I get the following error:

    'column' argument cannot be null. Parameter name: column

    Exception Details: System.ArgumentNullException: 'column' argument cannot be null. Parameter name: column
    Line 73:         TableStats.Columns.Add(myColumn)

    Author Comment

    TableStats is the correct name for myDataTable.
    LVL 25

    Expert Comment

    how is mycolumn defined
    LVL 24

    Accepted Solution

    Instead of this
    you need to have something that looks like this:

    Dim myColumn  as dataColumn
    LVL 24

    Expert Comment

    by:Jeff Certain
    Sorry... you don't need to define myColumn if you use the method above...otherwise you have to declare it, define it and add it...

    LVL 8

    Expert Comment

    Here is the sample Code:

    Public Class DataTableCreation
        Inherits System.Windows.Forms.Form

    #Region " Windows Form Designer generated code "

        Public Sub New()

            'This call is required by the Windows Form Designer.

            'Add any initialization after the InitializeComponent() call

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid
        Friend WithEvents Button1 As System.Windows.Forms.Button
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.DataGrid1 = New System.Windows.Forms.DataGrid
            Me.Button1 = New System.Windows.Forms.Button
            CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
            Me.DataGrid1.DataMember = ""
            Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
            Me.DataGrid1.Location = New System.Drawing.Point(32, 48)
            Me.DataGrid1.Name = "DataGrid1"
            Me.DataGrid1.Size = New System.Drawing.Size(336, 144)
            Me.DataGrid1.TabIndex = 0
            Me.Button1.Location = New System.Drawing.Point(136, 216)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(96, 24)
            Me.Button1.TabIndex = 1
            Me.Button1.Text = "Button1"
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(424, 266)
            Me.Name = "DataTableCreation"
            Me.Text = "DataTableCreation"
            CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()

        End Sub

    #End Region

        Dim myDataTable As DataTable
        Dim myColumn As DataColumn
        Dim Row As DataRow

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

            myColumn = myDataTable.Columns.Add("COL4", System.Type.GetType("System.Double"))

            For Each Row In myDataTable.Rows
                Row.Item("COL4") = "3"
            Next Row

        End Sub

        Private Sub DataTableCreation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            myDataTable = New DataTable("Group")

            myColumn = myDataTable.Columns.Add("COL1", System.Type.GetType("System.String"))
            myColumn = myDataTable.Columns.Add("COL2", System.Type.GetType("System.Double"))
            myColumn = myDataTable.Columns.Add("COL3", System.Type.GetType("System.Double"))

            myDataTable.Rows.Add(New Object() {"Name1", "1", "2"})
            myDataTable.Rows.Add(New Object() {"Name2", "1", "2"})
            myDataTable.Rows.Add(New Object() {"Name3", "1", "2"})

            DataGrid1.DataSource = myDataTable

        End Sub
    End Class

    Good Luck.

    Author Comment

    Chaosian was right. I needed to declare my datatype first.
    Thanks for all your help.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Article by: Kraeven
    Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
    I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now