如何使用 vb.net 更改数据表中的列数据类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50984380/
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
How to change column data type in a data table using vb.net
提问by Dalicino
How can I change the data type of data column from an input data table (already filled) in VB.NET, then I'll put the code in a Blue Prism Code Stage where I have in input:
如何从 VB.NET 中的输入数据表(已填充)更改数据列的数据类型,然后我会将代码放在 Blue Prism Code Stage 中输入:
Name of the field (column) that I want to change the data type
The data type that I want to convert
Input Collection (data table)
我要更改数据类型的字段(列)的名称
我要转换的数据类型
输入集合(数据表)
Example:
例子:
Dim InputDT As New DataTable
InputDT.Columns.Add(New DataColumn("test"))
dt.Columns("test").DataType = GetType(Date)
Thanks
谢谢
回答by Ahmed Abdelhameed
If the DataTable is already filled with data, you cannotchange the type of any of its columns. If you try to do that, you will receive an ArgumentExceptionwith a very straightforward message:
如果 DataTable 已经填充了数据,则不能更改其任何列的类型。如果您尝试这样做,您将收到ArgumentException一条非常简单的消息:
Cannot change DataType of a column once it has data.
一旦有数据,就不能更改列的数据类型。
A good alternative would be to create a new DataTable (or clone the existing one), change the column type, and then fill it with the data from the old DataTable.
一个不错的替代方法是创建一个新的 DataTable(或克隆现有的 DataTable),更改列类型,然后用旧 DataTable 中的数据填充它。
Something like this should work:
这样的事情应该工作:
Dim InputDT As New DataTable
InputDT.Columns.Add(New DataColumn("test"))
InputDT.Rows.Add("1/1/2018")
Dim clonedDT As DataTable = InputDT.Clone()
clonedDT.Columns("test").DataType = GetType(Date)
For Each row As DataRow In InputDT.Rows
clonedDT.ImportRow(row)
Next
Note that in order for this to work, the data in that column mustbe valid for the new type.
请注意,为了使其工作,该列中的数据必须对新类型有效。
Edit:
编辑:
To handle the case where the existing values cannot be casted to the new type, you can use a Try.. Catchstatement like the following:
要处理现有值无法转换为新类型的情况,您可以使用Try.. Catch如下语句:
' ...
Try
For Each row As DataRow In InputDT.Rows
clonedDT.ImportRow(row)
Next
Catch ex As ArgumentException
' An error occurred, use 'ex.Message' to display the error message. Example:
Console.WriteLine(ex.Message)
End Try

