does anyone know the best way to insert a column in a datatable at position 0?
-
1sometimes if you are adding column to the datatable after getting the data from db you may need to set it at the begging.– Wael DalloulCommented Aug 27, 2009 at 9:46
-
1im pusing the datatable into a bulk insert– GrantCommented Aug 27, 2009 at 10:59
-
9@Stefan, I believe the order of the columns is relevant when using Sql BulkCopy.– IAbstractCommented Dec 14, 2010 at 17:04
4 Answers
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;
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.
-
16single ligne statement aren't alway better. In this case I like it +1– RémiCommented Jul 15, 2013 at 15:54
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
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