2

I'm trying to reference a public property from a string. How can this be done in vb.net? I have the text value of "FirstName" stored in strucParam(i).TxtPropertyName.

This is what I'm currently doing:

Dim tmpValue As String
Dim ucAppName As UserControl_appName = CType(Parent.FindControl(strucParam(i).ParentFindControl), UserControl_appName)

tmpValue = ucAppName.FirstName.Text

How can I use the value in strucParam(i).TxtPropertyName so that I can remove ".FirstName" from my code? Thanks!

1 Answer 1

1

This is basically a duplicate of this question, but I'll answer it for you since you're a VB user and probably didn't consider C# in your searches.

Suppose you have an object of any type stored in a variable called objObject, and the name of the property stored in a variable called strPropertyName. You do the following:

tmpValue = objObject.GetType().GetProperty(strPropertyName).GetValue(objObject, Nothing)

As a final note: please, please consider dropping pseudo-Hungarian notation. It's of no value when working with a statically typed language like VB.NET.

Edit:

The FirstName property is in reality a text box. So don't I need to somehow reference .Text in the code?
tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing)

Try this:

Dim textBox as TextBox
Dim tmpValue as String

textBox = CType(ucAppName.GetType().GetProperty(strucParam(1).PropertyName).GetValue(objAppNav, Nothing), TextBox)
tmpValue = textBox.Text

Basically, you have to cast the value of the property to a TextBox type, then grab the Text property from it.

Sign up to request clarification or add additional context in comments.

3 Comments

I was unable to use null. I had to substitute it with Nothing. When running the following code, I get an "Object does not match target type" error. The FirstName property is in reality a text box. So don't I need to somehow reference .Text in the code? tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing)
@crjunk: my bad, I'm a C# guy and forgot to translate. I'll edit.
Thank you! Thank you! In honor of your help, I will no longer use pseudo-Hungarian notation. :) I had a typo in the code I posted here. My final solution was: Dim textBox As TextBox textBox = CType(ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(ucAppName, Nothing), TextBox)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.