I have:
DataTable Table = new DataTable;
SqlConnection = new System.Data.SqlClient.SqlConnection("Data Source=" + ServerName + ";Initial Catalog=" + DatabaseName + ";Integrated Security=SSPI; Connect Timeout=120");
SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
DataColumn column = DataTable.Columns[0];
What I want to do is:
Assume currently column.DataType.Name is "Double". I want it to become "Int32".
How do I achieve this?
Consider also altering the return type:
Once a
DataTable
has been filled, you can't change the type of a column.Your best option in this scenario is to add an
Int32
column to theDataTable
before filling it:Then you can clone the data from your original table to the new table:
Here's a post with more details.
I created an extension function which allows changing the column type of a DataTable. Instead of cloning the entire table and importing all the data it just clones the column, parses the value and then deletes the original.
You can use it like so:
The above code changes all the decimal columns to doubles.
I've taken a bit of a different approach. I needed to parse a datetime from an excel import that was in the OA date format. This methodology is simple enough to build from... in essence,
Delete the original column and rename to the new to match the old
While it is true that you cannot change the type of the column after the
DataTable
is filled, you can change it after you callFillSchema
, but before you callFill
. For example, say the 3rd column is the one you want to convert fromdouble
toInt32
, you could use: