2

Possible Duplicate:
How To Convert The DataTable Column type?

How can we change the datatable column type if table already have value?

Community
  • 1
  • 1
Shivi
  • 1,075
  • 9
  • 24
  • 42

1 Answers1

14

Changing data type of datatable after get filled is not possible but one of the work abound for this is clone datatable and change type

First way

//clone datatable     
DataTable dtCloned = dt.Clone();
//change data type of column
dtCloned.Columns[0].DataType = typeof(Int32);
//import row to cloned datatable
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

second way

and other way to do it is like this , fill schema first - than change column datatype and than fill datable

adapter.FillSchema(table, SchemaType.Source);
table.Columns[0].DataType = typeof (Int32);
adapter.Fill(table);

third way

one more way to do it is

System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Col1", typeof(int));
dt.Rows.Add(1);

System.Data.DataTable dt2 = new System.Data.DataTable();
dt2.Columns.Add("Col1", typeof(string));
dt2.Load(dt.CreateDataReader(), System.Data.LoadOption.OverwriteChanges);
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • It is worth mentioning that second way is worked for mine when I have get Data from database, and before populating in DataTable I have set adapter.FillSchema. like using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, Con)) { dataAdapter.FillSchema(DataTable, SchemaType.Source); DataTable.Columns[9].DataType = typeof(string); dataAdapter.Fill(DataTable); } – Faraz Ahmed May 17 '17 at 05:58