I want to convert string to other type.
The problem is that I know the type only in runtime.
I don’t want to use a Select case.
Is a better way?
More information:
I want to build a form at runtime.
So in an xml I have the controls for that form with all the properties that i want to set a value:
<Controls>
<Label>
<Text>Names</Text>
<AutoSize>False</AutoSize>
<Enabled>True</Enabled>
</Label>
<TextBox>
<Text>Id:</Text>
<Enabled>FALSE</Enabled>
</TextBox>
</Controls>
No my code is :
For Each elem As XElement In xmlDoc.Root.Element("Controls").Elements
Dim oType As Type
oType = FindType("System.Windows.Forms." & elem.Name.ToString) 'FindType is a function to return the type
Dim cnt As New Control
cnt = Activator.CreateInstance(oType)
For Each proper As XElement In elem.Elements
Dim propName As String = proper.Name.ToString
Dim myPropInfo As PropertyInfo = cnt.GetType().GetProperty(propName)
If myPropInfo IsNot Nothing Then
Dim val As String = proper.Value
' HERE SOMETHING TO CONVERT THE STRING TO myPropInfo.PropertyType
' Setting a value to the property
cnt.GetType().GetProperty(propName).SetValue(cnt, val, Nothing)
End If
Next
Me.FlowLayoutPanel1.Controls.Add(cnt)
Next
What you’re looking for is the
Convert.ChangeTypemethod, which receives two parameters, the string you’re converting from, and theTypeyou’re converting to: