如何使用vb.net更改数据表中的列数据类型 [英] How to change column data type in a data table using vb.net

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

问题描述

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

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:

  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

请注意,要使其正常工作,该列中的数据必须对于新类型有效.

Note that in order for this to work, the data in that column must be valid for the new type.

要处理无法将现有值强制转换为新类型的情况,可以使用如下所示的Try.. Catch语句:

To handle the case where the existing values cannot be casted 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

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

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