CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Oct 2006
    Posts
    28

    problem copying columns

    I've got a couple of listboxes which the user can move items from one to the other. When they're done moving the items, which are column names from a datatable, I want to show only the columns which have names in the first list box.

    the list box items look like this:

    01 surname
    02 firstname
    03 initials

    So I cut off the first part of the listbox item to get the column index

    Early on in the code I populate a datatable called dt and use the column names to fill the listbox. The part I've described above all seems to work fine.

    This bit doesn't:

    Code:
            Dim newdt As New DataTable()
            For i = 0 To ListBox1.Items.Count() - 1
                Dim mystr As String = ListBox1.Items(i).ToString().Substring(0, 2) 'here I'm cutting the index off the front of the string
                Dim myint As Short = Val(mystr) 'turning the index into a value
                newdt.Columns.Add(dt.Columns(myint))
            Next
    I get this error:
    An unhandled exception of type 'System.ArgumentException' occurred in system.data.dll

    Additional information: Column 'Surname' already belongs to another DataTable.
    I'm using .NET Framework 3.5

    I'm planning to be spontaneous tomorrow

  2. #2
    Join Date
    Dec 2005
    Location
    Waterloo ON
    Posts
    545

    Re: problem copying columns

    No, you can't add a column in another datatable to a new table. But you could use method "Clone" of DataTable class to do that.

  3. #3
    Join Date
    Oct 2005
    Location
    Islamabad, Pakistan
    Posts
    1,277

    Re: problem copying columns

    use the code to add a column to the new dataTable
    Code:
    newdt.Columns.Add(dt.Columns(myint).ColumnName, dt.Columns(myint).DataType)

  4. #4
    Join Date
    Oct 2006
    Posts
    28

    Re: problem copying columns

    Thank you aniskhan, your code creates the correct column headings for me, but no data. Do I need to add the data row by row too?
    I'm using .NET Framework 3.5

    I'm planning to be spontaneous tomorrow

  5. #5
    Join Date
    Feb 2005
    Location
    Israel
    Posts
    1,475

  6. #6
    Join Date
    Jun 2011
    Posts
    1

    Re: problem copying columns

    Superb!!!Nice work......correct solution 100%

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured