[Datable] change column datatype

S

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
 
S

Sam

hummm.... I've found out.
System.Integer does not exists, I should have done System.Int32 instead
but the compiler didn't complain
 
C

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
 
S

Sam

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

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
 
O

Oenone

Sam said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top