C# 如何更改类型数据表列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14278839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:17:46  来源:igfitidea点击:

How to change type datatable column

c#typesdatatable

提问by Shivi

Possible Duplicate:
How To Convert The DataTable Column type?

可能的重复:
如何转换 DataTable 列类型?

How can we change the datatable column type if table already have value?

如果表已经有值,我们如何更改数据表列类型?

回答by Pranay Rana

Changing data type of datatable after get filled is not possible but one of the work abound for this is clone datatable and change type

在填充后更改数据表的数据类型是不可能的,但其中一项工作是克隆数据表和更改类型

First way

第一种方式

//clone datatable     
DataTable dtCloned = dt.Clone();
//change data type of column
dtCloned.Columns[0].DataType = typeof(Int32);
//import row to cloned datatable
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}


second way

第二种方式

and other way to do it is like this , fill schema first - than change column datatype and than fill datable

和其他方法是这样的,首先填充模式-然后更改列数据类型然后填充数据

adapter.FillSchema(table, SchemaType.Source);
table.Columns[0].DataType = typeof (Int32);
adapter.Fill(table);


third way

第三种方式

one more way to do it is

另一种方法是

System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Col1", typeof(int));
dt.Rows.Add(1);

System.Data.DataTable dt2 = new System.Data.DataTable();
dt2.Columns.Add("Col1", typeof(string));
dt2.Load(dt.CreateDataReader(), System.Data.LoadOption.OverwriteChanges);