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

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

问题描述

我有:

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.Name 的是双师型的。我希望它成为的的Int32

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

我如何做到这一点?

感谢您为您的任何回应。

Thank you for your response if any.

推荐答案

您不能DataTable中充满数据后更改的数据类型。但是,您可以克隆的数据表,从previous数据表中的列类型和负载数据更改为克隆表如下图所示。

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);
}

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

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