[ACCEPTED]-How does one insert a column into a dataset between two existing columns?-dataset

Accepted answer
Score: 45

You can use the DataColumn.SetOrdinal() method for this purpose.

DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("column_1", typeof(string));
ds.Tables[0].Columns.Add("column_2", typeof(int));
ds.Tables[0].Columns.Add("column_4", typeof(string));
ds.Tables[0].Columns.Add("column_3", typeof(string));
//set column 3 to be before column 4


Score: 8

I used your suggestion to create an extention 2 method for the DataSet's DataColumnCollection:

public static void InsertAfter(this DataColumnCollection columns, 
                              DataColumn currentColumn, DataColumn newColumn)
    if (!columns.Contains(currentColumn.ColumnName))
       throw new ArgumentException(/** snip **/);

    //add the new column after the current one
    columns[newColumn.ColumnName].SetOrdinal(currentColumn.Ordinal + 1); 

I 1 can now write:

 dt = ds.Tables[0];
 dt.Columns.InsertAfter(dt.Columns["column_2"], new DataColumn("column_3"));
Score: 0

Based on https://stackoverflow.com/a/17372008/492336, I use SetOrdinal with IndexOf() to 2 insert bar before foo:


To insert it after foo just 1 add +1:


More Related questions