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

  • Thread starter Thread starter JC Voon
  • Start date Start date
J

JC Voon

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
 
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")
 
JC Voon said:
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
 
JC Voon said:
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.
 
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
 
Back
Top