views:

65

answers:

2

Hi all,

How to change Datatable columns oder in c#.

example:

am created sql table type order is Qty,Unit,Id but in program DataTable order is Id,Qty,Unit. In code Behind am directly pass DataTable to sql table type so the table order is different.

DataTable columns are :`Id,Qty,Unit.`  i want this to be  :`Qty,Unit,Id` 

please help

+5  A: 

Try to use the DataColumn.SetOrdinal method. For example:

dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1); 
MAKKAM
This also works for me.
Koekiebox
@MAKKAM :by giving as you told,table structure changed to `Qty,Id,Unit` only.I want like this `Qty,Unit,Id`.
Vyas
Ofc, you should use this method for all of the columns except the last.
MAKKAM
+1  A: 

One of the way is creating your own DataTable like,

DataTable dt = new DataTable();

dt.Columns.Add("Qty",typeof(int));
dt.Columns.Add("Unit",typeof(decimal));
dt.Columns.Add("Id",typeof(Guid));

and

foreach(DataRow item in yourDataTable.Rows)
{
object[] row = new object[]
{
item.Qty, //or Convert.ToInt32(item[x]),
item.Unit, //or Convert.ToDecimal(item[y]),
item.Id //or ....
};
dt.Rows.Add(row);
}
Serkan Hekimoglu
This will end up using double the amount of memory than before.
ck