Home > Uncategorized > Changing the dataType of a DataColumn after it has data

Changing the dataType of a DataColumn after it has data

I was looking into a problem where a datagrid had a datetime field that was being sorted alphabetically rather than chronologically.
 
This was happening because the datacolumn was a string rather than a DateTime, it had to remain a string for formatting purposes. You can’t change it by Just saying DataColumn.DateType=… because the column had data already: However, this is how I changed it:
 

private void changeColumnType(string columnName,System.Type newType,ref DataTable inputTable)

{

DataColumn dcUpdated;

dcUpdated = inputTable.Columns.Add("_temp_", newType);

foreach(DataRow drUpdated in inputTable.Rows)

{

drUpdated["_temp_"] = drUpdated[columnName].ToString();

}

inputTable.Columns.Remove(inputTable.Columns[columnName]);

dcUpdated.ColumnName = columnName;

}

 
 
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment