Can’t change data type? Clone DataTable and convert columns
You try to change the DataType of a DataColumn in a DataTable. Unfortunately, once a DataTable is populated with data, its DataType cannot be modified directly.
To achieve your goals, a slightly different approach is required: data cloning. Here’s how to do it:
<code>DataTable dtCloned = dt.Clone();</code>
<code>dtCloned.Columns[0].DataType = typeof(Int32); // 假设原始列为 Double</code>
<code>foreach (DataRow row in dt.Rows) { dtCloned.ImportRow(row); }</code>
This method allows you to convert the DataType of the column after it is populated with data. Remember that the original DataTable remains unchanged and you will use the modified cloned DataTable instead.
The above is the detailed content of How Can I Change a DataTable Column's DataType After It's Populated?. For more information, please follow other related articles on the PHP Chinese website!