views:

5299

answers:

3

I'm trying to insert a column into an existing DataSet using C#.

As an example I have a DataSet defined as follows:

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));

later on in my code I am wanting to insert a column between column 2 and column 4.

DataSets have methods for adding a column but I can't seem to find the best way in insert one.

I'd like to write something like the following...

...Columns.InsertAfter("column_2", "column_3", typeof(string))

The end result should be a data set that has a table with the following columns: column_1 column_2 column_3 column_4

rather than: column_1 column_2 column_4 column_3 which is what the add method gives me

surely there must be a way of doing something like this.

Edit...Just wanting to clarify what I'm doing with the DataSet based on some of the comments below:

I am getting a data set from a stored procedure. I am then having to add additional columns to the data set which is then converted into an Excel document. I do not have control over the data returned by the stored proc so I have to add columns after the fact.

+1  A: 

copy the first two columns into a new dataset, then add the third column, and add the remaining columns.

You could wrap that in an InsertAfter function if necessary.

PaulMorel
+12  A: 

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
ds.Tables[0].Columns[3].SetOrdinal(2);
lomaxx
Thanks, exactly what I needed!
Mike Post
+1  A: 

Thanks lomaxx!

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

public static void InsertAfter(this DataColumnCollection columns, 
                              DataColumn currentColumn, DataColumn newColumn)
{

    if (columns.Contains(currentColumn.ColumnName))
    {
        columns.Add(newColumn);
        //add the new column after the current one
        columns[newColumn.ColumnName].SetOrdinal(currentColumn.Ordinal + 1); 
    }
    else
    {
        throw new ArgumentException(/** snip **/);
    }
}

I can now write:

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