121

does anyone know the best way to insert a column in a datatable at position 0?

3
  • 1
    sometimes if you are adding column to the datatable after getting the data from db you may need to set it at the begging. Commented Aug 27, 2009 at 9:46
  • 1
    im pusing the datatable into a bulk insert
    – Grant
    Commented Aug 27, 2009 at 10:59
  • 9
    @Stefan, I believe the order of the columns is relevant when using Sql BulkCopy.
    – IAbstract
    Commented Dec 14, 2010 at 17:04

4 Answers 4

212

You can use the following code to add column to Datatable at postion 0:

    DataColumn Col   = datatable.Columns.Add("Column Name", System.Type.GetType("System.Boolean"));
    Col.SetOrdinal(0);// to put the column in position 0;
110

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

1
  • 16
    single ligne statement aren't alway better. In this case I like it +1
    – Rémi
    Commented Jul 15, 2013 at 15:54
3
using System.Data;
...

//Example to define how to do :
DataTable dt = new DataTable();   
dt.Columns.Add("ID");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Address");
dt.Columns.Add("City");
               
//  The table structure is:
//ID    FirstName   LastName    Address     City
    
//Now we want to add a PhoneNo column after the LastName column. 
//For this we use the SetOrdinal function, as in:
dt.Columns.Add("PhoneNo").SetOrdinal(3);
    
//3 is the position number and positions start from 0.
    
//Now the table structure will be:
// ID    FirstName   LastName    PhoneNo    Address     City

0

Just an addendum.

This is also a way to set the column type of an existing empty column, in a non empty datatable. (.net does not allow setting the column type af a column directly for a table with rows, currently, even if the column is 'empty')

I needed it for filling data of an unknown type into a datatable, where the first row of data might have null-value for a column.

Later when the first non-null value for a column appears, you can then remove the 'empty' column with RemoveAt and re-add a new one with the same name and the now known type at the same position with the described Add and SetOrdinal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.