Change Ordinal Position of DataColumn in DataTable in

Well I got asked this question by someone and I thought for sure there would be an easy solution. At least at the 1.1 level of the .NET framework I have not found an answer. (GE Healthcare where I work we still use 1.1). Hoping there will be an easy solution for this in 3.5. Anyway, brute force seems to be the only approach that works with the DataColumnCollection class. Here is what I told him….

Join me on Facebook

Public Function ReOrderTable(ByVal dt_in As DataTable, ByVal ColumnOrder() As Integer) As DataTable
        Dim dt As New DataTable
        Dim dr As DataRow
        Dim c, c_in, key() As DataColumn
        Dim i As Integer
        dt.TableName = dt_in.TableName
        ‘ copy the schema of each columns
        For i = 0 To UBound(ColumnOrder)
            c_in = dt_in.Columns(ColumnOrder(i))
            c = New DataColumn(c_in.ColumnName)
            c.DataType = c_in.DataType
            c.AllowDBNull = c_in.AllowDBNull
            c.MaxLength = c_in.MaxLength
            c.AutoIncrement = c_in.AutoIncrement
            c.AutoIncrementSeed = c_in.AutoIncrementSeed
            c.AutoIncrementStep = c_in.AutoIncrementStep
        ‘ copy the primary keys
        ReDim key(UBound(dt_in.PrimaryKey))
        For i = 0 To UBound(dt_in.PrimaryKey)
            key(i) = dt.Columns(dt_in.PrimaryKey(i).ColumnName)
        dt.PrimaryKey = key
        ‘ copy the data
        For Each dr In dt_in.Rows()
        Return dt
    End Function


  1. #1 by Ivan on February 22, 2009 - 11:49 am

    Hi.Good piece of code.I cannot understand how there is a Datatable.Clone method and not a DataColumn.Clone method. I imagine that\’s because Datacolumn has some properties that are Table dependent.If you use 3.5, you have Datacolumn.setOrdinal(int) to change Datacolumn position in a Datatable.Greetings.

  2. #2 by Kelly on February 22, 2009 - 6:29 pm

    Yep unfortunately not all of us get to use the latest in the Framework depending on the company you work for. But oh well…. 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: