Normally, When we want to add an extra column to a dataset
DataSet ds = new DataSet();
DataColumn column = new DataColumn("extraCol", System.Type.GetType("System.String"));
ds.Tables[j].Columns.Add(column);
Suppose we fill the dataset from a database and this dataset has 4 columns. The above two statements will add a 5th column called "extraCol" to the ds.
But this addition will always happen at the end. I mean, after the 4 original columns, you will have this extraCol.
What if you want this "extraCol" column to be added in the 3rd position??
Here's what I did ( And it works!!)
First I get a count of columns from the dataset and subtract the position which will get me the exact column number:
int columnNo = ds.Tables[j].Columns.Count - 1;
this will get the column No as 3. ( total number of columns in ds: 4). Subtract 1, you get 3.
Then do:
column.SetOrdinal(columnNo);
That's all. You now have the column "extraCol" at position 3.
Here's the code:
DataSet ds = new DataSet();
DataColumn column = new DataColumn("extraCol", System.Type.GetType("System.String"));
ds.Tables[j].Columns.Add(column);
int columnNo = ds.Tables[j].Columns.Count - 1;
column.SetOrdinal(columnNo);
For more info on the SetOrdinal Method see this link:
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.setordinal.aspx
I hope this is useful.
Awesome post,Thanks buddy
ReplyDelete