Thursday, May 16, 2013

Changing Datatype of a Datatable column in Asp.net

Hello in this post i will show how to change datatable column datatype.

1. Suppose i have a datatable with some data in it and i want to change the datatype of one of the column from string to int.

2. As we know after the datatable is filled with data we cannot change the datatype of the column.

3. Hence i will make a clone of the Main datatable so that only structure get copied and not data.
And now i will change the datatype in the newly created datatable(Cloned) and then will import the data from the Main datatable into new datatable(Cloned).

Example:

Below is code to change the Datatable Column datatype from string to int:


DataTable ClonedDatatable = MainDatatable.Clone();
ClonedDatatable.Columns[1].DataType = typeof(Int32);
foreach (DataRow row in MainDatatable.Rows) 
{
    ClonedDatatable.ImportRow(row);
}


No comments:

Post a Comment