Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to guid in DataColumn

How do you convert a DataColumn of GUIDs set as type string to a DataColumn of GUIDs where the type is Guid? A column in the source data has the wrong type and I cannot change it there.

like image 201
Alex Angas Avatar asked Jan 05 '10 06:01

Alex Angas


2 Answers

Once the datatable has been populated with data, you can't change the column type. There's a few approaches you can take:

  1. If you're using a DataAdapter to fill the table, you can use DataAdapter.FillSchema() to get the structure of the table first. Then you can modify the column type, and then fill it with data.

  2. Take the initial table and clone it, change the column type on the new table, and then use DataTable.ImportRow() to import each row from the old table.

  3. Create a new column, copy the values from the old column to the new column, and delete the old column.

like image 194
womp Avatar answered Nov 18 '22 12:11

womp


You can add to womp's answer the following option:

  1. After you get the table full of the data you can add a new DataColumn to the Columns of the data table this way:

    DataColumn dc = new DataColumn("GUIDColumnName",typeof(Guid),"StringColumnName");
    DataTableObj.Columns.Add(dc);
    

This will not have a performance hit if your data volume is huge.

like image 2
Mostafa Elmoghazi Avatar answered Nov 18 '22 14:11

Mostafa Elmoghazi