如何更改包含数据的 DataTable 中的列数据类型? [英] How to change column data type in a DataTable that contains data?

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

问题描述

如何从 VB.NET 中的输入 DataTable(已填充)更改数据列的数据类型?然后,我会将代码放在 Blue Prism Code Stage 中,我在其中输入:

How can I change the data type of data column from an input DataTable (already filled) in VB.NET? Then, I'll put the code in a Blue Prism Code Stage where I have in input:

  1. 我想改变数据类型的字段(列)名称

  1. Name of the field (column) that I want to change the data type

我要转换的数据类型

输入集合(数据表)

示例:

Dim InputDT As New DataTable
InputDT.Columns.Add(New DataColumn("test"))
dt.Columns("test").DataType = GetType(Date)

推荐答案

如果 DataTable 已经填充了数据,您不能更改其任何列的类型.如果您尝试这样做,您将收到带有非常简单的消息的 ArgumentException:

If the DataTable is already filled with data, you cannot change the type of any of its columns. If you try to do that, you will receive an ArgumentException with a very straightforward message:

一旦有数据就不能改变列的数据类型.

Cannot change DataType of a column once it has data.

一个不错的替代方法是创建一个新的 DataTable(或克隆现有的 DataTable),更改列类型,然后用旧 DataTable 中的数据填充它.

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.

这样的事情应该可以工作:

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

请注意,为了使其正常工作,该列中的数据必须对新类型有效.要处理现有值无法转换为新类型的情况,您可以使用 Try..Catch 语句,如下所示:

Note that in order for this to work, the data in that column must be valid for the new type. To handle the case where the existing values cannot be cast to the new type, you can use a Try.. Catch statement like the following:

' ...
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

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

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