Change DataColumn data type in DataTable
When working with data in a DataTable, you may encounter situations where you need to modify the data type of a specific column to accommodate a different data format.
Consider the following scenario: a DataTable is populated with data from a SQL table and the first column, originally defined as a 'Double' data type, needs to be converted to an 'Int32'.
Code snippet:
<code class="language-csharp">DataTable dt = new DataTable(); using (SqlConnection conn = new SqlConnection(...)) { using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM " + tableName, conn)) { adapter.FillSchema(dt, SchemaType.Source); adapter.Fill(dt); } }</code>
Solution:
By default, DataTable does not allow modifying the data type of a column after filling it with data. However, there is a workaround to clone the DataTable and modify the data type of the columns. The modified columns can then be repopulated with data from the original table.
Code snippet:
<code class="language-csharp">// 创建一个具有所需列数据类型的克隆 DataTable DataTable dtCloned = dt.Clone(); dtCloned.Columns[0].DataType = typeof(Int32); // 使用原始表中的数据填充克隆表 foreach (DataRow row in dt.Rows) { dtCloned.ImportRow(row); }</code>
With this approach, you can effectively change the data type of a column even after filling the DataTable with data.
The above is the detailed content of How Can I Change a DataTable Column's DataType After Data Has Been Populated?. For more information, please follow other related articles on the PHP Chinese website!