Home All Groups Group Topic Archive Search About

[Datable] change column datatype

Author
14 Apr 2005 10:52 AM
Sam
Hi

Here is my code :

Code:
Dim dt As New DataTable
dt.Columns.Add.ColumnName = "New"
dt.Columns("New").DataType = System.Type.GetType("System.String")
dt.Columns.Add.ColumnName = "Id"
dt.Columns("Id").DataType = System.Type.GetType("System.Integer")
Dim Row As DataRow = dt.NewRow()
Dim rc As DataRowCollection = dt.Rows
rc.InsertAt(Row, 0)

Defining the ype of the column "New" doesn't crash the application but
defining the type of the column "Id" to integer raises the following
exception:

"System.ArgumentException: Cannot change DataType of a column once it
has data.

But there is no data in it since I've just created the column...
What's wrong with my code ??

Thx

Author
14 Apr 2005 11:04 AM
Sam
hummm.... I've found out.
System.Integer does not exists, I should have done System.Int32 instead
but the compiler didn't complain
Author
14 Apr 2005 12:06 PM
Oenone
Sam wrote:
> System.Integer does not exists, I should have done System.Int32
> instead but the compiler didn't complain

It didn't complain because you used the System.Type.GetType() method, which
takes a string as its parameter. You passed a valid string, so the compiler
is happy. The fact that the string contained an invalid value for this
function couldn't be picked up until run time.

If you use the GetType() function as in Cor's example, you pass an actual
type rather than a string containing the name of the type. That way the
compiler is able to spot the error at compile time instead of when the code
runs.

--

(O)enone
Author
14 Apr 2005 11:05 AM
Cor Ligthert
Sam,

Are you sure you get that error, because it is more likely that you get an
error that System.integer does not exist.

However, here the same code what is not such a C# look alike as in the
samples on MSDN and works easier because you can use the intelisence

\\\
Dim dt As New DataTable
dt.Columns.Add.ColumnName = "New"
dt.Columns("New").DataType = GetType(System.String)
dt.Columns.Add.ColumnName = "Id"
dt.Columns("Id").DataType = GetType(System.Int32)
Dim Row As DataRow = dt.NewRow()
Dim rc As DataRowCollection = dt.Rows
rc.InsertAt(Row, 0)
///

(I assume that you know that in the constructor from the datatable you can
as well do)

\\\
dt.Columns.Add.ColumnName("New", GetType(System.String))
///

I hope this helps,


Cor
Author
14 Apr 2005 11:30 AM
Sam
thanks. as I said the compiler didn't complain about that. This is the
reason I couldn't find out about this error.
Author
14 Apr 2005 11:35 AM
Cor Ligthert
Sam,

> thanks. as I said the compiler didn't complain about that. This is the
> reason I couldn't find out about this error.

I was sending in the same time a you, so how could I know you had seen that
already, however watch those easier methods I showed you.

:-)

Cor
Author
14 Apr 2005 12:03 PM
Sam
I will
Thanks Cor