By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,312 Members | 1,877 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,312 IT Pros & Developers. It's quick & easy.

How to convert a string value to a data type during runtime ?

P: n/a
Hi:
I need to convert a value reading from XML file to specific type,
the XMLstring is look like this:

<Field1 DataType="System.Int32", Value="123">
Dim t As Type = Type.GetType("System.Int32")

Dim i as integer = CType("123", t ) ---> the 2nd param not accept t

Any idea ?

Thansk
JCVoon

Nov 21 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
On 2005-07-20, JC Voon <jc*******@yahoo.com> wrote:
Hi:
I need to convert a value reading from XML file to specific type,
the XMLstring is look like this:

<Field1 DataType="System.Int32", Value="123">
Dim t As Type = Type.GetType("System.Int32")

Dim i as integer = CType("123", t ) ---> the 2nd param not accept t

Any idea ?

Thansk
JCVoon


Dim i As Integer = Convert.ToInt32 ("123")
Dim i As Integer = Integer.Parse ("123")

--
Tom Shelton [MVP]
Nov 21 '05 #2

P: n/a
"JC Voon" <jc*******@yahoo.com> schrieb
Hi:
I need to convert a value reading from XML file to specific type,
the XMLstring is look like this:

<Field1 DataType="System.Int32", Value="123">
Dim t As Type = Type.GetType("System.Int32")

Dim i as integer = CType("123", t ) ---> the 2nd param not accept t

Any idea ?

System.String implements the IConvertible interface. Check out it's ToType
function:

Dim t As Type = Type.GetType("System.Int32")
Dim o As Object = DirectCast("123", IConvertible).ToType(t, Nothing)
o is declared "as Object" because you don't know the type. If you would know
it, you could declare it 'as integer' and use CInt or Integer.Parse.
Armin

Nov 21 '05 #3

P: n/a
"JC Voon" <jc*******@yahoo.com> wrote in message
news:42***************@msnews.microsoft.com...
Dim t As Type = Type.GetType("System.Int32")
Dim i as integer


Essentially, what you /want/ to do is ...

i = Convert.ChangeType( "123", t )

.... but, perversely, ChangeType() returns an Object which you
then have to cast /again/, as in

i = DirectCast( _
Convert.ChangeType( "123", t ) _
)

HTH,
Phill W.
Nov 21 '05 #4

P: n/a
Hi TomShelton, Armin Zinger, Phill. W:

Thanks for the answer, both Armin and Phill. method is exactly what i
want.
Dim t As Type = Type.GetType("System.Int32")
Dim o As Object = DirectCast("123", IConvertible).ToType(t, Nothing)

and

Dim t As Type = Type.GetType("System.Int32")
Dim o As Object = Convert.ChangeType( "123", t )
Thanks
JCVoon

Nov 21 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.