1

I have a DataTable with 2 columns in it. I would like to insert another column to the start, and move those 2 columns to the right by 1.

 DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];

Any ideas how I could do this?

Thanks.

viv_acious
  • 2,429
  • 9
  • 34
  • 55
  • This question has already been answered, please search before posting a question. http://stackoverflow.com/questions/1339880/c-sharp-datatable-insert-column-at-position-0 – Ryan Gunn Mar 28 '13 at 05:11
  • Thanks for letting me know - I couldn't find it before – viv_acious Mar 28 '13 at 05:21

2 Answers2

6

Try this.

DataColumn column = dtCurrentTable.Columns.Add("Column Name", typeof(<<The data type of your column>>));
column.SetOrdinal(0);// to put the column in position 0;
Sandeep
  • 5,581
  • 10
  • 42
  • 62
  • Thanks sandeep. Do you know how I can fill in this new column with one same value until it reaches the last row of all the other columns? – viv_acious Mar 28 '13 at 05:13
  • 1
    I didn't understand what you're trying to achieve. – Sandeep Mar 28 '13 at 06:10
  • Excellent solution Sandeep. +1! A little more concise way to do the same thing: myDataSet.Tables[0].Columns.Add("NewColumn"); myDataSet.Tables[0].Columns[myDataSet.Tables[0].Columns.Count - 1].SetOrdinal(0); – Jeff Apr 08 '21 at 21:46
1

Do Something like this>>

DataTable workTable = new DataTable("Customers");

    DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
    workCol.AllowDBNull = false;
    workCol.Unique = true;

    workTable.Columns.Add("CustLName", typeof(String));
    workTable.Columns.Add("CustFName", typeof(String));
    workTable.Columns.Add("Purchases", typeof(Double));

Hope its helpfull.

Freelancer
  • 9,008
  • 7
  • 42
  • 81
  • Thanks Freelancer! Do you know how I can fill the new column with one same value until it reaches the end of rows of the other existing columns? – viv_acious Mar 28 '13 at 05:16