does anyone know the best way to insert a column in a datatable at position 0?
Asked
Active
Viewed 1.2e+01k times
117
-
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 Dalloul Aug 27 '09 at 09:46
-
1im pusing the datatable into a bulk insert – Grant Aug 27 '09 at 10:59
-
9@Stefan, I believe the order of the columns is relevant when using Sql BulkCopy. – IAbstract Dec 14 '10 at 17:04
3 Answers
205
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;

Wael Dalloul
- 22,172
- 11
- 48
- 57
107
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.

Amit Bisht
- 4,870
- 14
- 54
- 83

CigarDoug
- 1,438
- 1
- 15
- 29
3
//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 iin:
dt.Columns.Add("PhoneNo").SetOrdinal(3);
//3 is the position number and positions start from 0.`enter code here`
//Now the table structure will be:
// ID FirstName LastName PhoneNo Address City