Dynamic casting

M

Matt Weaver

I'm trying to setup a sub that would assign the properties of a
webcontrol based on data in a table. I've setup a routine which looks
like this:

Private Sub SetObjectProperty(ByRef obj As Object, _
ByValPropertyName As String, _
ByVal PropertyValue As String)
Dim wType As System.Type = obj.GetType
Dim wProp As Reflection.PropertyInfo = _
wType.GetProperty(PropertyName)
wProp.SetValue(obj, PropertyValue, Nothing)
End Sub

It works well when the property is a string, but when it's boolean I get
this error: "Object of type 'System.String' cannot be converted to
type 'System.Boolean'"

I can get the type of the property (in this case, System.Boolean), I
have the value I'd get if I used .ToString(). .NET has to have some
function that'd dynamically cast the string back to Boolean (or whatever
data type), right? I'm trying to avoid a giant if-then structure (if
type = system.boolean then cast as boolean).

TIA!
-Matt
 
S

sloan

I think you wrote it correct, but because of the way the eval works...
you'll have to hack in some case statements.

Here is my code... notice I check the "CanWrite". That probably isn't your
issue, but I list it there anyways.

I think you'll need to hack in some case statements on the type
unforunately.


'''''''''the next loop is basically a cloning mechanism.

''''''''Dim prop As PropertyInfo

''''''''For Each prop In AssemblyProperties

'''''''' If prop.CanWrite Then ' only update properties which can be written
to

'''''''' Dim indivReportProperty As PropertyInfo =
newObject.GetType().GetProperty(prop.Name)

'''''''' If Not (indivReportProperty Is Nothing) Then 'handle the case where
the objects are not perfect copies of one another

'''''''' 'this sets the "new object" property to the getvalue of the "old
object"

'''''''' indivReportProperty.SetValue(newObject, prop.GetValue(newObject,
Nothing), Nothing)

'''''''' End If

'''''''' End If

''''''''Next prop
 
K

Karl Seguin [MVP]

Well, you can use Convert.ChangeType(obj, type);

For situations like this, I often find it better to ass in a
NameValueCollection collection into the object, and let it figure out how to
do thing:

//pass the values using an interface:
((ISomeInterface)obj).Parameters = keyValueCollection;


//use the values:
if (Parameters["count"] != null)
{
_count = Int32.Parse(Parameters["count"]);
}
else
{
throw new Exception("count parameter expected");
}


Karl
 
M

Matt Weaver

Convert.ChangeType worked for me. I'll keep the rest of your message in
mind if it breaks with more complicated object types.
 

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

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top