如何更改数据表中数据列的数据类型? [英] How To Change DataType of a DataColumn in a DataTable?

查看:31
本文介绍了如何更改数据表中数据列的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

DataTable Table = new DataTable;
SqlConnection = new System.Data.SqlClient.SqlConnection("Data Source=" + ServerName + ";Initial Catalog=" + DatabaseName + ";Integrated Security=SSPI; Connect Timeout=120");

SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);

DataColumn column = DataTable.Columns[0];

我想做的是:

假设当前 column.DataType.NameDouble".我希望它变成Int32".

Assume currently column.DataType.Name is "Double". I want it to become "Int32".

我如何实现这一目标?

推荐答案

Datatable 填充数据后,您无法更改 DataType.但是,您可以克隆数据表,更改列类型并将数据从以前的数据表加载到克隆的表中,如下所示.

You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.

DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

这篇关于如何更改数据表中数据列的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆