Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing populated DataTable column data types

Tags:

c#

.net

ado.net

I have a System.Data.DataTable which is populated by reading a CSV file which sets the datatype of each column to string.

I want to append the contents of the DataTable to an existing database table - currently this is done using SqlBulkCopy with the DataTable as the source.

However, the column data types of the DataTable need to be changed to match the schema of the target database table, handling null values.

I am not very familiar with ADO.NET so have been searching for a clean way of doing this?

Thanks.

like image 213
TonE Avatar asked Mar 29 '10 14:03

TonE


People also ask

How can I change the DataType of a column in DataTable?

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 the DataTable before filling it: dataTable = new DataTable("Contact"); dataColumn = new DataColumn("Id"); dataColumn. DataType = typeof(Int32); dataTable.

How do you define DataTable columns?

You create DataColumn objects within a table by using the DataColumn constructor, or by calling the Add method of the Columns property of the table, which is a DataColumnCollection. The Add method accepts optional ColumnName, DataType, and Expression arguments and creates a new DataColumn as a member of the collection.


1 Answers

I wrote this generic function to do the job, it works very well for me:

public static bool ChangeColumnDataType(DataTable table, string columnname, Type newtype)
{
    if (table.Columns.Contains(columnname) == false)
        return false;

    DataColumn column= table.Columns[columnname];
    if (column.DataType == newtype)
        return true;

    try
    {
        DataColumn newcolumn = new DataColumn("temporary", newtype);
        table.Columns.Add(newcolumn);
        foreach (DataRow row in table.Rows)
        {
            try
            {
                row["temporary"] = Convert.ChangeType(row[columnname], newtype);
            }
            catch
            {
            }
        }
        table.Columns.Remove(columnname);
        newcolumn.ColumnName = columnname;
    }
    catch (Exception)
    {
        return false;
    }

    return true;
}

You can just copy the code and put it in a class(MyClass here) , and use it like this as an example:

MyClass.ChangeColumnDataType(table, "GEOST", typeof (int));
like image 156
www.diwatu.com Avatar answered Sep 30 '22 05:09

www.diwatu.com