Tuesday, December 6, 2011

System.ArgumentException: Cannot change DataType of a column once it has data.

I got the error above when I tried to cast a DataColumn full of int values to DataColumn of a string type like so:

int statusIndex = myDataTable.Columns.IndexOf("Status");

myDataTable.Columns[statusIndex].DataType = typeof(string);

   

I had to solve the problem the hard way:

myDataTable.Columns.Add("StatusString", typeof(string));

myDataTable.Rows.ForEach(row =>

{

   row["StatusString"] = row["Status"].ToString();

});

myDataTable.Columns.Remove("Status");

int statusIndex = myDataTable.Columns.IndexOf("StatusString");

myDataTable.Columns[statusIndex].ColumnName = "Status";

No comments:

Post a Comment