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;

}

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: